<template>
  <div class="notice">
    <MomTable
      ref="MomTable"
      row-key="id"
      :row-selection="rowSelectionMain"
      :columns="tableColumns"
      :data-source="tableData"
      :query-param="queryForm"
      :query-param-item="queryFormItem"
      :total="total"
      :page.sync="page"
      :action-buttons="tableAction"
      @edit="handleEdit"
      @delete="handleDelete"
      @beforeSearch="beforeSearch"
      @search="searchPageData"
    >
      <template slot="toolbar">
        <a-button v-if="hasAuth('NOTICE_MANAGEMENT:ADD')" @click="handAdd">
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <a-button
          v-if="hasAuth('NOTICE_MANAGEMENT:BATCH_DELETE')"
          type="danger"
          icon="delete"
          @click="handDelete"
        >
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </template>
      <template slot="noticeCategory" slot-scope="text, record">
        {{ formatData(noticeTypeList, record.noticeCategory) }}
      </template>
      <template slot="noticeStatus" slot-scope="text, record">
        <span
          :style="
            record.noticeStatus === 'INIT' ? 'color: #d45f5f' : 'color: #0fd19c'
          "
        >
          {{ formatData(noticeStatusList, record.noticeStatus) }}
        </span>
      </template>
    </MomTable>
    <MegaDrawer
      :visible="drawerVisible"
      :title="$t('RELEASE')"
      width="40%"
      @close="handleCloseDrawer"
    >
      <template slot="main">
        <MomTable
          ref="MomTableDrawer"
          row-key="id"
          :columns="tableColumnsDrawer"
          :data-source="tableDataDrawer"
          :row-selection="rowSelection"
          :mega-extend="{
            rowIndex: {
              width: 70,
            },
            rowAction: {
              width: 70,
            },
          }"
          :action-buttons="tableActionDrawer"
          @delete="handleDeleteDrawer"
        >
          <template slot="toolbar">
            <a-button
              v-if="hasAuth('NOTICE_MANAGEMENT:ADD')"
              @click="handAddDrawer"
            >
              <a-icon type="plus" /> {{ $t("ADD") }}
            </a-button>
          </template>
          <template slot="receiverType" slot-scope="text, record">
            <a-select v-model="record.receiverType" style="width: 100%">
              <a-select-option
                v-for="(item, index) in drawerTypeList"
                :key="index"
                :value="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </template>
          <template slot="receiverTargetCode" slot-scope="text, record">
            <a-input
              v-if="record.receiverType === 'OVERALL'"
              v-model="record.receiverTargetCode"
              :disabled="record.receiverType === 'OVERALL'"
            ></a-input>
            <SelectUser
              v-if="record.receiverType === 'USER'"
              ref="selectRoleRef"
              v-model="record.receiverTargetCode"
              row-key="id"
              show-key="name"
              style="position: relative"
              :multiple="false"
              @confirm="(...args) => getReturnData(...args, record)"
            />
            <SelectRole
              v-if="record.receiverType === 'ROLE'"
              ref="selectRoleRef"
              v-model="record.receiverTargetCode"
              row-key="id"
              show-key="roleName"
              :multiple="false"
              @confirm="(...args) => getReturnDataRule(...args, record)"
            />
            <SelectUserGroup
              v-if="record.receiverType === 'USER_GROUP'"
              ref="selectUserGroup"
              v-model="record.receiverTargetCode"
              show-key="groupName"
              :show-clear="false"
              :multiple="false"
              @confirm="(...args) => getReturnDataUserGroup(...args, record)"
            />
            <a-tree-select
              v-if="record.receiverType === 'DEPT'"
              v-model="record.receiverTargetCode"
              :replace-fields="treeProps"
              tree-check-strictly
              :tree-data="treeData"
              allow-clear
              style="width: 100%"
            />
          </template>
        </MomTable>
      </template>
      <footer slot="footer">
        <div></div>
        <a-button type="primary" :disabled="isRelease" @click="handRelease()">
          <a-icon type="to-top" />{{ $t("RELEASE") }}
        </a-button>
        <a-button @click="handleCloseDrawer">
          <Icon type="icon-dir-f-rollback" :size="18" />{{ $t("CANCEL") }}
        </a-button>
      </footer>
    </MegaDrawer>
  </div>
</template>
<script>
import { Drawer as MegaDrawer, Icon } from "@mega-design/ui-vue";
import { v1 as uuidv1 } from "uuid";
import ApiConstant from "@/api/ApiConstant";
import SelectUser from "@/components/SelectUser";
import SelectRole from "@/components/SelectRole";
import SelectUserGroup from "@/components/SelectUserGroup";

export default {
  components: {
    MegaDrawer,
    SelectUser,
    SelectRole,
    SelectUserGroup,
    Icon,
  },
  data() {
    return {
      treeProps: {
        value: "id",
        children: "children",
        label: "label",
      },
      drawerVisible: false,
      isRelease: false,
      page: 1, // 分页第几页
      total: 0, // 数据表格总条数
      tableData: [],
      departmentList: [],
      tableDataDrawer: [],
      noticeId: "", // 公告ID
      // 查询的表单的配置项
      queryForm: {
        noticeTitle: "",
        noticeCategory: "",
        noticeStatus: "",
        time: [],
      },
      treeData: [],
      noticeStatusList: [],
      noticeTypeList: [],
      drawerTypeList: [],
      selectedRowKeys: [],
      selectedRowKeysMain: [],
      selectedRowsList: [],
      tableAction: [
        this.hasAuth("NOTICE_MANAGEMENT:EDIT") && "edit",
        this.hasAuth("NOTICE_MANAGEMENT:DELETE") && "delete",
        (h, { record }, a, b) =>
          record.noticeStatus !== "PUBLISHED" && (
            <span onClick={() => this.handleRelease(record)}>
              <a-icon type="to-top" title={this.$t("RELEASE")} />
            </span>
          ),
        (h, { record }, a, b) =>
          record.noticeStatus === "PUBLISHED" && (
            <span type="text" onClick={() => this.handleWinthdraw(record)}>
              <a-icon type="undo" title={this.$t("WITHDRAW")} />
            </span>
          ),
      ],
      tableActionDrawer: [this.hasAuth("NOTICE_MANAGEMENT:DELETE") && "delete"],
    };
  },
  computed: {
    rowSelectionMain() {
      return {
        selectedRowKeys: this.selectedRowKeysMain,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeysMain = selectedRowKeys;
        },
      };
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
          this.selectedRowsList = selectedRows;
        },
      };
    },
    queryFormItem() {
      return this.$observable("queryFormItem", {
        noticeTitle: {
          label: () => this.$t("NOTICE_TITLE"), // 公告标题
        },
        noticeCategory: {
          itemType: "select",
          label: () => this.$t("NOTICE_CATEGORY"), // 公告类别
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
        },
        noticeStatus: {
          label: () => this.$t("NOTICE_STATUS"), // 公告状态
          itemType: "select",
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
        },
        time: {
          label: () => this.$t("RELEASE_TIME"),
          itemType: "range",
        },
      });
    },
    tableColumns() {
      return [
        {
          dataIndex: "noticeCategory",
          title: () => this.$t("NOTICE_CATEGORY"),
          scopedSlots: { customRender: "noticeCategory" },
          minWidth: 400,
        },
        {
          dataIndex: "noticeTitle",
          sorter: false,
          title: this.$t("NOTICE_TITLE"),
          minWidth: 400,
        },
        {
          dataIndex: "noticeStatus",
          title: () => this.$t("NOTICE_STATUS"),
          scopedSlots: { customRender: "noticeStatus" },
          sorter: false,
          minWidth: 200,
        },
        {
          dataIndex: "publishUser",
          title: this.$t("PUBLISHER"),
          sorter: false,
          width: 200,
        },
        {
          dataIndex: "publishTime",
          title: () => this.$t("RELEASE_TIME"),
          sorter: false,
          width: 200,
        },
      ];
    },
    tableColumnsDrawer() {
      return [
        {
          dataIndex: "receiverType",
          title: () => this.$t("TYPE"),
          sorter: false,
          scopedSlots: { customRender: "receiverType" },
          minWidth: 140,
        },
        {
          dataIndex: "receiverTargetCode",
          sorter: false,
          title: this.$t("RECEIVER_NAME"),
          scopedSlots: { customRender: "receiverTargetCode" },
          minWidth: 340,
        },
      ];
    },
  },
  methods: {
    beforeSearch() {
      this.getDictByCode("DIC:MSG:NOTICE_STATUS").then((res) => {
        this.queryFormItem.noticeStatus.options = res.data.data;
        this.noticeStatusList = res.data.data;
      });
      this.getDictByCode("DIC:MSG:NOTICE_CATEGORY").then((res) => {
        this.queryFormItem.noticeCategory.options = res.data.data;
        this.noticeTypeList = res.data.data;
      });
      this.getDictByCode("DIC:MSG:NOTICE_RECEIVER_TYPE").then((res) => {
        this.drawerTypeList = res.data.data;
      });
      const params = {
        enableFlag: "Y",
      };
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/org/tree`, { params })
        .then((res) => {
          this.treeData = res.data.data;
        });
    },
    // 格式化数据
    formatData(data, status) {
      const result = data.find((item) => item.value === status.toString());
      return result ? result.label : "";
    },
    // 获取选择用户组件返回数据
    getReturnData(selectedRowKeys, selectedRows, row) {
      if (selectedRows.length > 0) {
        // eslint-disable-next-line no-param-reassign
        row.receiverTargetCode = selectedRows[0].id;
      } else {
        // eslint-disable-next-line no-param-reassign
        row.receiverTargetCode = "";
      }
    },
    // 获取选择角色组件返回数据
    getReturnDataRule(selectedKeys, selectedRows, row) {
      if (selectedRows.length > 0) {
        // eslint-disable-next-line no-param-reassign
        row.receiverTargetCode = selectedRows[0].id;
      } else {
        // eslint-disable-next-line no-param-reassign
        row.receiverTargetCode = "";
      }
    },
    getReturnDataUserGroup(selectedKeys, selectedRows, row) {
      if (selectedRows.length > 0) {
        // eslint-disable-next-line no-param-reassign
        row.receiverTargetCode = selectedRows[0].id;
      } else {
        // eslint-disable-next-line no-param-reassign
        row.receiverTargetCode = "";
      }
    },
    searchPageData(params) {
      const req = {
        ...params,
        publishStartDate: this.queryForm.time?.length
          ? this.formatDate(
              this.queryForm.time?.length && this.queryForm.time[0]
            ) || null
          : null,
        publishEndDate: this.queryForm.time?.length
          ? this.formatDate(
              this.queryForm.time?.length && this.queryForm.time[1]
            ) || null
          : null,
      };
      delete req.time;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/notice/search`, { params: req })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = parseFloat(res.data.data.total);
        });
    },
    handAdd() {
      this.$router.push({
        path: "/upms/service/message/notice/add",
      });
    },
    handleEdit(row) {
      this.$router.push({
        path: "/upms/service/message/notice/edit",
        query: {
          id: row.id,
        },
      });
    },
    formatDate(value) {
      const date = new Date(value);
      const y = date.getFullYear();
      let MM = date.getMonth() + 1;
      MM = MM < 10 ? `0${MM}` : MM;
      let d = date.getDate();
      d = d < 10 ? `0${d}` : d;
      return `${y}-${MM}-${d}`;
    },
    handDelete() {
      if (this.selectedRowKeysMain.length > 0) {
        this.$confirm({
          title: this.$t("DELETE"),
          content: this.$t("DELETE_INFO"),
          okType: "warning",
          okText: this.$t("CONFIRM"),
          cancelText: this.$t("CANCEL"),
          centered: false,
          icon: "close-circle",
          onOk: () => {
            this.$axios
              .delete(`${ApiConstant.PREFIX_CORE}/api/notice/batch-delete`, {
                params: {
                  ids: this.selectedRowKeysMain.join(","),
                },
              })
              .then((res) => {
                this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
                this.selectedRowKeysMain = [];
                this.$refs.MomTable?.query();
              });
          },
        });
      } else {
        this.$message.error(this.$t("SELECT_ONE_DATA"));
      }
    },
    // 表格行内删除
    handleDelete(row) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okType: "warning",
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.$axios
            .delete(`${ApiConstant.PREFIX_CORE}/api/notice/${row.id}`)
            .then((res) => {
              this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    handleDeleteDrawer(row) {
      this.$confirm({
        title: this.$t("DELETE"),
        content: this.$t("DELETE_INFO"),
        okType: "warning",
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "close-circle",
        onOk: () => {
          this.tableDataDrawer.forEach((item, index) => {
            if (item.id === row.id) {
              this.tableDataDrawer.splice(index, 1);
            }
          });
        },
      });
    },
    // 发布按钮点击
    handleRelease(row) {
      this.drawerVisible = true;
      this.noticeId = row.id;
      this.tableDataDrawer = [
        {
          id: uuidv1(),
          receiverType: "OVERALL",
          receiverTargetCode: "",
        },
      ];
    },
    // 撤回按钮点击
    handleWinthdraw(row) {
      this.$axios
        .put(`${ApiConstant.PREFIX_CORE}/api/notice/revoke/${row.id}`)
        .then((res) => {
          this.$message.success(this.$t("WITHDRAWAL_SUCCEED"));
          this.$refs.MomTable?.query();
        });
    },
    handleCloseDrawer() {
      this.drawerVisible = false;
    },
    handAddDrawer() {
      this.tableDataDrawer.push({
        id: uuidv1(),
        receiverType: "OVERALL",
        receiverTargetCode: "",
      });
    },
    handRelease() {
      const req = {
        noticeReceiverList: [],
        noticeId: this.noticeId,
      };
      this.isRelease = true;
      if (this.selectedRowsList.length > 0) {
        this.selectedRowsList.forEach((item) => {
          req.noticeReceiverList.push({
            receiverTargetCode: item.receiverTargetCode,
            receiverType: item.receiverType,
          });
        });
      } else {
        this.tableDataDrawer.forEach((item) => {
          req.noticeReceiverList.push({
            receiverTargetCode: item.receiverTargetCode,
            receiverType: item.receiverType,
          });
        });
      }
      const result = req.noticeReceiverList.map(
        (v) => v.receiverType !== "OVERALL" && v.receiverTargetCode
      );
      const isTrue = result.includes("");
      if (!isTrue) {
        this.$axios
          .put(`${ApiConstant.PREFIX_CORE}/api/notice/publish`, req)
          .then((res) => {
            this.isRelease = false;
            this.$message.success(this.$t("RELEASE_SUCCESS"));
            this.drawerVisible = false;
            this.$refs.MomTable?.query();
            this.$EventBus.$emit("noticeInit");
          });
      } else {
        this.isRelease = false;
        this.$message.error(this.$t("REQUIRED_INFO"));
      }
    },
    // 新增详情
    handleAddItem() {
      this.$refs.selectDepartmentGroup.openDialog();
    },
  },
};
</script>
