/* eslint-disable prettier/prettier */
<template>
  <div class="box-main">
    <MomTable
      ref="MomTable"
      row-key="id"
      :row-selection="rowSelection"
      :columns="tableColumns"
      :data-source="tableData"
      :query-param="queryForm"
      :query-param-item="queryFormItem"
      :total="total"
      :page.sync="page"
      :action-buttons="actionButtons"
      :show-enable-flag="true"
      @edit="handleEdit"
      @delete="handleDelete"
      @search="searchPageData"
      @enable="
        (record) =>
          handleStatus(
            { status: 'Y', id: record.id },
            'ENABLED',
            'ENABLED_DATA_INFO',
            'ENABLE_SUCCESS'
          )
      "
      @disable="
        (record) =>
          handleStatus(
            { status: 'N', id: record.id },
            'DISABLED',
            'DISABLED_DATA_INFO',
            'DISABLE_SUCCESS'
          )
      "
    >
      <div slot="toolbar" class="button-top-table">
        <a-button
          v-if="hasAuth('RECEIVING_GROUP_MANAGEMENT:ADD')"
          type="primary"
          @click="handleAdd"
        >
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <a-button
          v-if="hasAuth('RECEIVING_GROUP_MANAGEMENT:BATCH_DELETE')"
          type="danger"
          icon="delete"
          @click="handDelete"
        >
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </div>

      <template slot="groupType" slot-scope="text, record">
        <span>{{ formatData(groupTypeList, record.groupType) }}</span>
      </template>
      <template slot="enableFlag" slot-scope="text">
        <span :class="text === 'Y' ? 'text-success' : 'text-error'">
          {{ getAttrValue(statusList, text) }}
        </span>
      </template>
    </MomTable>
    <MegaDrawer
      :visible="drawerVisible"
      :title="form.id ? $t('EDIT') : $t('ADD')"
      width="520"
      @close="handleCloseDrawer"
    >
      <template slot="main">
        <a-form-model
          ref="addForm"
          layout="vertical"
          :model="form"
          :rules="rules"
        >
          <a-row>
            <a-col :span="24">
              <a-form-model-item
                :label="$t('RECEIVING_GROUP_CODE')"
                prop="groupCode"
              >
                <a-input v-model="form.groupCode" :disabled="form.id !== ''" />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item
                :label="$t('RECEIVING_GROUP_NAME')"
                prop="groupName"
              >
                <a-input v-model="form.groupName" :disabled="form.id !== ''" />
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item
                :label="$t('RECEIVING_GROUP_MODE')"
                prop="groupType"
              >
                <a-select v-model="form.groupType" :disabled="form.id !== ''">
                  <a-select-option
                    v-for="(item, index) in groupTypeList"
                    :key="index"
                    :value="item.value"
                  >
                    {{ item.label }}
                  </a-select-option>
                </a-select>
              </a-form-model-item>
            </a-col>
            <a-col :span="24">
              <a-form-model-item :label="$t('DESCRIBE')" prop="remark">
                <a-input v-model="form.remark" type="textarea" />
              </a-form-model-item>
            </a-col>
          </a-row>
        </a-form-model>
        <MomTable
          ref="MomTableDrawer"
          row-key="id"
          :columns="tableColumnsDrawer"
          :data-source="tableDataDrawer"
          :action-buttons="actionButtonsItem"
          :pagination="false"
          @delete="handleDeleteItem"
        >
          <div
            v-if="form.groupType === 'ORG'"
            slot="toolbar"
            class="button-top-table"
          >
            <a-button type="primary" @click="handleAddItem">
              {{ $t("ADD") }}
            </a-button>
          </div>
          <div v-else slot="toolbar" class="button-top-table">
            <SelectUserGroup
              ref="selectUserGroup"
              :show-clear="false"
              :default-selected-keys="selectUserList"
              @confirm="getReturnData"
            >
              <div class="button-top-table">
                <a-button type="primary">
                  {{ $t("ADD") }}
                </a-button>
              </div>
            </SelectUserGroup>
          </div>
        </MomTable>
      </template>
      <footer slot="footer">
        <a-button type="primary" @click="handleSave()">
          <Icon type="icon-cur-save_1" :size="18" />{{ $t("SAVE") }}
        </a-button>
        <a-button @click="handleCloseDrawer">
          <Icon type="icon-dir-f-rollback" :size="18" />{{ $t("CANCEL") }}
        </a-button>
      </footer>
    </MegaDrawer>
    <select-department-group
      ref="selectDepartmentGroup"
      :selected-data="selectUserList"
      @returnData="getReturnData"
    />
  </div>
</template>
<script>
import { Drawer as MegaDrawer, Icon } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import SelectUserGroup from "@/components/SelectUserGroup";
import SelectDepartmentGroup from "./components/selectDepartmentGroup";

export default {
  components: { SelectUserGroup, SelectDepartmentGroup, MegaDrawer, Icon },
  data() {
    const validatePass = (rule, value, callback) => {
      if (value === "") {
        callback(new Error(this.$t("COMPANY_CREDIT_CODE")));
      } else if (this.form.creditCode !== "") {
        const patrn = /^[0-9A-Z]+$/;
        if (
          patrn.test(this.form.creditCode) === false ||
          this.form.creditCode.length !== 18
        ) {
          callback(new Error(this.$t("COMPANY_CREDIT_CODE")));
        } else {
          callback();
        }
      }
    };
    return {
      title: "", // 弹框标题
      drawerVisible: false, // 新增修改的弹框
      drawerVisibleView: false, // 查看弹框
      // 查询sort
      tableData: [], // 表格数据
      page: 1, // 分页第几页
      total: 0, // 数据表格总条数
      form: {
        id: "",
        groupCode: "",
        groupName: "",
        groupType: "USER_GROUP",
        targetIds: [],
        remark: "",
      },
      rules: {
        groupName: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        groupType: [
          {
            required: true,
            message: this.$t("PLACESELECT"),
            trigger: "change",
          },
        ],
      },
      rulesConfig: {
        propertyCode: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
        propertyValue: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
        ],
      },
      groupTypeList: [], // 类型列表
      statusList: [], // 状态列表
      // 查询的表单的配置项
      queryForm: {
        groupType: "",
        groupCode: "",
        groupName: "",
      },
      actionButtons: [
        this.hasAuth("RECEIVING_GROUP_MANAGEMENT:EDIT") && "edit",
        this.hasAuth("RECEIVING_GROUP_MANAGEMENT:DELETE") && "delete",
      ],
      actionButtonsItem: ["delete"],
      selectUserList: [], // 当前所有的用户列表
      tableDataDrawer: [],
      isShowOperation: true,
      selectedRowKeys: [],
    };
  },
  computed: {
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    queryFormItem() {
      return this.$observable("queryFormItem", {
        groupType: {
          itemType: "select",
          label: () => this.$t("RECEIVING_GROUP_MODE"),
          options: [],
          optionsProps: {
            label: "label",
            value: "value",
          },
        },
        groupCode: {
          label: () => this.$t("RECEIVING_GROUP_CODE"),
        },
        groupName: {
          label: () => this.$t("RECEIVING_GROUP_NAME"),
        },
      });
    },
    tableColumns() {
      return [
        {
          dataIndex: "groupCode",
          sorter: false,
          title: () => this.$t("RECEIVING_GROUP_CODE"),
          minWidth: 210,
        },
        {
          dataIndex: "groupName",
          title: () => this.$t("RECEIVING_GROUP_NAME"),
          minWidth: 210,
        },
        {
          dataIndex: "groupType",
          sorter: false,
          title: () => this.$t("RECEIVING_GROUP_MODE"),
          scopedSlots: { customRender: "groupType" },
          width: 150,
        },
        {
          dataIndex: "enableFlag",
          title: () => this.$t("STATUS"),
          sorter: false,
          scopedSlots: { customRender: "enableFlag" },
          width: 120,
        },
        // 更新人员
        {
          dataIndex: "updateBy",
          sorter: false,
          title: () => this.$t("UPDATE_BY"),
          width: 210,
        },
        // 更新时间
        {
          dataIndex: "updateTime",
          sorter: false,
          title: () => this.$t("UPDATE_TIME"),
          width: 210,
        },
      ];
    },
    tableColumnsDrawer() {
      return [
        {
          sorter: false, // 隐藏排序
          dataIndex: "targetName",
          title: () => this.$t("RECIPIENT"),
        },
      ];
    },
  },
  mounted() {
    this.queryDictData();
  },
  methods: {
    // 获取选择用户组件返回数据
    getReturnData(selectedRowKeys, selectedRows) {
      // eslint-disable-next-line no-multi-assign
      this.tableDataDrawer = this.selectUserList = [];
      if (selectedRowKeys.length > 0) {
        this.selectUserList = selectedRowKeys || [];
        if (selectedRows && selectedRows.length > 0) {
          let tempObj;
          this.tableDataDrawer = selectedRows.map((item) => {
            tempObj = {
              id:
                // eslint-disable-next-line no-nested-ternary
                this.form.groupType === "ORG"
                  ? item.id
                  : item.id
                  ? item.id
                  : item.groupCode,
              targetName:
                this.form.groupType === "ORG" ? item.label : item.groupName,
            };
            return tempObj;
          });
        }
      }
    },
    getDepartmentReturnData() {},
    queryDictData() {
      return Promise.all([
        this.getDictByCode(`DIC:COMMON:ENABLE_FLAG`), // 启用状态
        this.getDictByCode(`DIC:MSG:RECEIVE_GROUP_TYPE`), // 服务类型
      ]).then(([enableStatusRes, groupTypeRes]) => {
        this.statusList = enableStatusRes.data.data;
        this.groupTypeList = groupTypeRes.data.data;
        this.queryFormItem.groupType.options = groupTypeRes.data.data;
      });
    },
    formatData(data, curItem) {
      const result = data.find((item) => item.value === curItem.toString());
      return result ? result.label : "";
    },
    searchPageData(params) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/msg/receiver-group/search`, {
          params,
        })
        .then((res) => {
          this.tableData = res.data.data.records;
          this.total = parseFloat(res.data.data.total);
        });
    },
    // 新增按钮的点击
    handleAdd() {
      this.clearData();
      this.$set(this, "form", {
        id: "",
        groupCode: "",
        groupName: "",
        groupType: "USER_GROUP",
        targetIds: [],
        remark: "",
      });
      this.drawerVisible = true;
    },
    // 编辑按钮点击
    handleEdit(row) {
      this.clearData();
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/msg/receiver-group/get-by-id/${row.id}`
        )
        .then((res) => {
          this.form = { ...res?.data?.data };
          this.isShowOperation = res?.data?.data?.groupType !== "ORG";
          const targetIds = res?.data?.data?.itemList;

          if (targetIds && targetIds.length > 0) {
            this.tableDataDrawer = targetIds;
            targetIds.forEach((item) => {
              this.selectUserList.push(item.id);
            });
          }
          this.drawerVisible = true;
        });
    },
    // 监听点击保存事件
    handleSave() {
      this.$refs.addForm.validate((valid) => {
        if (valid) {
          this.form.targetIds = [];
          if (this.tableDataDrawer.length > 0) {
            this.tableDataDrawer.forEach((item) => {
              this.form.targetIds.push(item.id);
            });
          }
          const req = {
            ...this.form,
          };
          if (!this.form?.id) {
            this.$axios
              .post(`${ApiConstant.PREFIX_CORE}/api/msg/receiver-group`, req)
              .then((res) => {
                this.$message.success(this.$t("ADD_SUCCESS"));
                this.$refs.MomTable?.query();
                this.drawerVisible = false;
              });
          } else {
            this.$axios
              .put(`${ApiConstant.PREFIX_CORE}/api/msg/receiver-group`, req)
              .then((res) => {
                this.$message.success(this.$t("EDIT_SUCCESS"));
                this.$refs.MomTable?.query();
                this.drawerVisible = false;
              });
          }
        }
      });
    },
    handDelete() {
      if (this.selectedRowKeys.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/msg/receiver-group/batch-delete`,
                {
                  params: {
                    ids: this.selectedRowKeys.join(","),
                  },
                }
              )
              .then((res) => {
                this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
                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/msg/receiver-group/${row.id}`
            )
            .then((res) => {
              this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 关闭弹框
    handleCloseDrawer() {
      this.$refs.addForm.clearValidate();
      this.drawerVisible = false;
    },
    // 新增详情
    handleAddItem() {
      this.$refs.selectDepartmentGroup.openDialog();
    },
    // 删除详情
    handleDeleteItem(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: () => {
          const index = this.tableDataDrawer.findIndex(
            (item) => item.id === row.id
          );
          // eslint-disable-next-line camelcase
          const index_select = this.selectUserList.findIndex(
            (item) => item === row.id
          );
          this.tableDataDrawer.splice(index, 1);
          this.selectUserList.splice(index_select, 1);
        },
      });
    },
    // 启用、禁用
    handleStatus(record, titleText, contentText, tips) {
      this.$confirm({
        title: this.$t(titleText),
        content: this.$t(contentText),
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "exclamation-circle",
        onOk: () => {
          const { id, status } = record;
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/msg/receiver-group/enable/${id}/${status}`
            )
            .then((res) => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    // 清除数据
    clearData() {
      this.selectUserList = [];
      this.tableDataDrawer = [];
    },
  },
};
</script>
<style lang="less" scoped>
/deep/.mega-design-drawer__footer {
  border-top: none;
  button:last-child {
    margin-left: 10px;
    i {
      margin-right: 5px;
    }
  }
}
</style>
