<template>
  <div class="announce-manage card">
    <el-form
      ref="form"
      :model="searchForm"
      size="mini"
      v-enter-submit="search"
      @submit.native.prevent
      :inline="true"
    >
      <el-form-item label="创建时间">
        <el-date-picker
          style="width: 164px"
          v-model="searchForm.time"
          align="right"
          type="date"
          placeholder="选择日期"
          value-format="yyyy-MM-dd"
        ></el-date-picker>
        <!-- <el-input v-model="searchForm.time"></el-input> -->
      </el-form-item>
      <el-form-item label="创建人">
        <el-select
          v-model="searchForm.creator"
          placeholder="请选择"
          clearable
          filterable
        >
          <el-option
            v-for="user in userList"
            :key="user.id"
            :label="user.realName"
            :value="user.id"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label>
        <el-button
          type="primary"
          native-type="submit"
          @click="search()"
        >
          查询
        </el-button>
      </el-form-item>
      <el-form-item label>
        <el-button type="success" @click="editDialog()"
          >新增</el-button
        >
      </el-form-item>
    </el-form>
    <div class="table_wrap" style="padding: 0">
      <table-view
        :sourceData="sourceData"
        :serialNumber="false"
        :tableColumns="tableColumns"
      ></table-view>
    </div>
    <pagination
      :setValue="setpaginationOptions"
      :options="paginationOptions"
    />
    <el-dialog
      :title="isEdit ? '编辑' : '新增'"
      :close-on-click-modal="false"
      :visible.sync="dialogVisible"
      width="900px"
    >
      <el-form
        :model="editForm"
        :inline="true"
        label-width="80px"
        :rules="addrules"
        size="mini"
        ref="editForm"
      >
        <el-form-item
          label="标题"
          size="small"
          prop="title"
        >
          <el-input
            style="width: 530px"
            v-model="editForm.title"
          ></el-input>
          <el-checkbox
            style="margin-left: 20px"
            v-model="editForm.titleWeight"
            label="粗体"
          ></el-checkbox>
        </el-form-item>
        <el-form-item label>
          <el-color-picker
            style="vertical-align: text-top"
            v-model="editForm.titleColor"
          ></el-color-picker>
        </el-form-item>

        <br />
        <el-form-item label="置顶">
          <el-switch
            v-model="editForm.priority"
          ></el-switch>
        </el-form-item>
      </el-form>
      <v-editor
        filename="files"
        v-model="editForm.content"
        ref="wangeditor"
        height="300px"
      />
      <div slot="footer">
        <el-button
          @click="dialogVisible = false"
          size="mini"
          >取 消</el-button
        >
        <el-button
          type="primary"
          @click="submit"
          size="mini"
          >确 定</el-button
        >
      </div>
    </el-dialog>
    <el-dialog
      :visible.sync="releaseVisible"
      :close-on-click-modal="false"
      title="发布"
      width="600px"
    >
      <el-checkbox
        :indeterminate="isIndeterminate"
        v-model="checkAll"
        @change="handleCheckAllChange"
        >全选</el-checkbox
      >
      <div style="margin: 15px 0"></div>
      <el-checkbox-group
        v-model="checkedCompany"
        @change="handleCheckedCompanyChange"
      >
        <el-checkbox
          style="width: 100px"
          v-for="c in releaseList"
          :label="c.id"
          :key="c.id"
          >{{ c.apiName }}</el-checkbox
        >
      </el-checkbox-group>
      <span slot="footer">
        <el-button
          size="mini"
          @click="releaseVisible = false"
          >取消</el-button
        >
        <el-button
          size="mini"
          @click="confirmRelease"
          type="primary"
          >确认</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>
<script>
import Editor from '@/components/wangeditor/index.vue'
import tableView from '@/common/components/base/tableView.vue'
import { get, post } from '@/common/api/axios'
import { getSystemUserList } from '@/common/api/system'
export default {
  name: 'system_announce_manage',
  components: { 'v-editor': Editor, tableView },
  data() {
    return {
      checkAll: false,
      isIndeterminate: false,
      checkedCompany: [],
      userList: [],
      pageSize: 50,
      currentPage: 1,
      total: 1,
      paginationOptions: {
        pageSize: 100,
        currentPage: 1,
        total: 0,
      },
      addrules: {
        title: [
          {
            required: true,
            message: '请输入标题',
            trigger: 'blur',
          },
        ],
      },
      sourceData: [],
      searchForm: {},
      isEdit: false,
      dialogVisible: false,
      editForm: {
        title: '',
      },
      defaultEditFrom: {
        title: '',
        enableFlag: false,
        content: '',
        priority: false,
      },
      releaseVisible: false,
      releaseList: [],
    }
  },
  mounted() {
    this.getList()
    this.getSystemUserList()
  },
  computed: {
    tableColumns() {
      return [
        {
          label: '标题',
          key: 'title',
          align: 'left',
          render: (item) => (
            <span
              style={{
                color: item.titleColor,
                fontWeight: item.titleWeight ? 'bold' : '',
              }}
            >
              {item.title}
            </span>
          ),
        },
        { label: '创建人', key: 'creatorName' },
        { label: '创建时间', key: 'creationTime' },
        { label: '更新时间', key: 'updateTime' },
        {
          label: '是否发布',
          key: 'enableFlag',
          width: 100,
          render: (item) => (
            <span>
              {item.enableFlag ? '已发布' : '未发布'}
            </span>
          ),
        },
        {
          label: '操作',
          width: 100,
          render: (item) => (
            <div>
              {!item.enableFlag && (
                <span
                  class="icon-view icon-edit-view"
                  title="编辑"
                  onClick={() => this.editDialog(item)}
                >
                  <i class="el-icon-edit"></i>
                </span>
              )}
              {!item.enableFlag && (
                <span
                  class="icon-view icon-primary-view"
                  title="发布"
                  onClick={() => this.release(item)}
                >
                  <i class="el-icon-s-promotion"></i>
                </span>
              )}
              {!item.enableFlag && (
                <span
                  class="icon-view icon-del-view"
                  title="删除"
                  onClick={() => this.deleteAnnounces(item)}
                >
                  <i class="el-icon-delete"></i>
                </span>
              )}
            </div>
          ),
        },
      ]
    },
  },
  methods: {
    handleCheckAllChange(val) {
      this.checkedCompany = val
        ? this.releaseList.map((e) => e.id)
        : []
      this.isIndeterminate = false
    },
    handleCheckedCompanyChange(value) {
      const checkedCount = value.length
      this.checkAll =
        checkedCount === this.releaseList.length
      this.isIndeterminate =
        checkedCount > 0 &&
        checkedCount < this.releaseList.length
    },
    search() {
      this.getList()
    },
    async getSystemUserList() {
      try {
        const res = await getSystemUserList()
        this.userList = res.data
      } catch (e) {
        console.error(e)
      }
    },
    setpaginationOptions(opt) {
      for (const key in opt) {
        this.paginationOptions[key] = opt[key]
      }
      this.getList()
    },
    async getList() {
      try {
        const { pageSize, currentPage } =
          this.paginationOptions
        const res = await post('sys/announcement/list', {
          pageSize,
          currentPage,
          ...this.searchForm,
        })
        if (res.code !== 200) return
        this.sourceData = res.data.records
        this.paginationOptions.total = res.data.total
      } catch (e) {
        console.error(e)
      }
    },
    currentChange(i) {
      this.currentPage = i
      this.getList()
    },
    async editDialog(item) {
      if (item) {
        try {
          const res = await get(
            'sys/announcement/get/' + item.id,
          )
          if (res.code !== 200) return
          this.editForm = {
            ...this.editForm,
            ...res.data,
          }
          this.isEdit = true
        } catch (e) {
          console.error(e)
        }
      } else {
        this.editForm = JSON.parse(
          JSON.stringify(this.defaultEditFrom),
        )
        this.$nextTick(() => {
          this.$refs.editForm.clearValidate()
        })
        this.isEdit = false
      }
      this.dialogVisible = true
    },
    async submit() {
      try {
        await this.$refs.editForm.validate()
      } catch {
        return
      }

      try {
        const url = this.isEdit
          ? 'sys/announcement/edit'
          : 'sys/announcement/add'
        const res = await post(url, { ...this.editForm })
        if (res.code !== 200) return
        this.$message.success(res.message)
        this.dialogVisible = false
        this.getList()
      } catch (e) {
        console.error(e)
      }
    },
    async enableChange(item, val) {
      try {
        const res = await post('sys/announcement/edit', {
          id: item.id,
          enableFlag: val,
        })
        if (res.code !== 200) return
        this.$message.success(res.message)
        this.getList()
      } catch (e) {
        console.error(e)
      }
    },
    async release(item) {
      try {
        const res = await post('sys/domain/list')
        if (res.code !== 200) return
        this.releaseList = res.data
        this.rowId = item.id
        this.checkedCompany = []
        this.releaseVisible = true
      } catch (e) {
        console.error(e)
      }
    },
    async deleteAnnounces(item) {
      try {
        const res = await get(
          'sys/announcement/delete/' + item.id,
        )
        if (res.code !== 200) return
        this.$message.success(res.message)
        this.getList()
      } catch (e) {
        console.error(e)
      }
    },
    async confirmRelease() {
      if (this.checkedCompany.length === 0) {
        return this.$message.warning('请至少选择一条记录')
      }
      try {
        const res = await post('sys/announcement/publish', {
          id: this.rowId,
          dataSourcelist: this.checkedCompany,
        })
        if (res.code !== 200) return
        this.$message.success(res.message)
        this.releaseVisible = false
        this.getList()
      } catch (e) {
        console.error(e)
      }
    },
  },
}
</script>
<style scoped>
.announce-manage {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 10px 20px 0;
  overflow: hidden;
}
</style>
