<template>
  <div>
    <span v-if="showSlot" @click="openDialog">
      <slot>
        <a-input
          ref="blurInput"
          read-only
          :value="value || defaultValue"
          :placeholder="$t('PLACESELECT')"
        >
          <a-icon slot="suffix" type="down" />
        </a-input>
      </slot>
      <a-icon
        v-show="showClear && (value || defaultValue)"
        type="close-circle"
        theme="filled"
        class="closeIcon"
        @click.stop="handleClear"
      />
    </span>
    <MomModalTable
      ref="MomModalTable"
      :modal-props="{
        title: $t('FLOW_DIALOG'),
        visible: visible,
        wrapClassName: 'select-btn-permission-modal',
      }"
      :modal-listeners="{
        ok: handleConfirm,
        cancel: closeDialog,
      }"
      :table-props="{
        rowKey: rowKey,
        columns: tableColumns,
        dataSource: tableData,
        megaExtend: { rowAction: false },
        rowSelection,
        pagination: false,
        showUtilOperator: false,
        wholeExtraHeight: 82,
        customRow: (record) => {
          return {
            on: {
              click: () => handleRowClick(record),
            },
          };
        },
      }"
      :table-listeners="{
        search: searchPageData,
        'update:page': (current) => {
          page = current;
        },
      }"
    >
      <!-- <span slot="toolbar">
        <a-button type="primary" icon="plus">自定义按钮</a-button>
      </span> -->
      <span slot="tableCustomName" slot-scope="text, row">
        <a-input v-model="row.customName" />
      </span>
      <span slot="tableCommentChange" slot-scope="text, row">
        <template v-if="row.commentIsRequired">
          <a-select v-model="row.commentChange">
            <a-select-option key="Y" value="Y">
              {{ $t("REQUIRED") }}
            </a-select-option>
            <a-select-option key="N" value="N">
              {{ $t("NOT_FILL") }}
            </a-select-option>
          </a-select>
        </template>
        <span v-else>
          {{ text === "Y" ? $t("REQUIRED") : "" }}
          {{ text === "N" ? $t("NOT_FILL") : "" }}
        </span>
      </span>
    </MomModalTable>
  </div>
</template>
<script>
import { uniqBy } from "lodash";
import ApiConstant from "@/api/ApiConstant";
import MomModalTable from "@/components/MomModalTable";

export default {
  components: {
    MomModalTable,
  },
  props: {
    type: {
      type: String,
      require: true,
      default: "todo",
    },
    // 需要展示的key
    showKey: {
      type: String,
      default: "defaultName",
    },
    // 回传的key
    rowKey: {
      type: String,
      default: "id",
    },
    multiple: {
      type: Boolean,
      default: true,
    },
    // 是否显示slot
    showSlot: {
      type: Boolean,
      default: true,
    },
    // 是否显示清除按钮
    showClear: {
      type: Boolean,
      default: true,
    },
    defaultSelectedKeys: {
      type: Array,
      default() {
        return [];
      },
    },
    defaultSelectedRows: {
      type: Array,
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      visible: false, // 弹框显示、隐藏
      tableData: [],
      selectedKeys: [],
      selectedPageRows: {},
      value: undefined,
    };
  },
  computed: {
    defaultValue() {
      if (this.defaultSelectedKeys?.length) {
        return this.defaultSelectedKeys.join();
      }
      if (this.defaultSelectedRows?.length) {
        return this.defaultSelectedRows
          .map((item) => item[this.showKey])
          .join();
      }
      return undefined;
    },
    selectedRows() {
      let checked = Object.values(this.selectedPageRows).reduce(
        (res, item) => res.concat(item),
        []
      );

      const selectedRowsTmp = this.defaultSelectedRows.filter((item) =>
        this.selectedKeys.includes(item[this.rowKey])
      );

      if (this.multiple) {
        checked = uniqBy(checked.concat(selectedRowsTmp), this.rowKey);
      } else if (checked.length === 0) {
        checked.concat(selectedRowsTmp);
      }
      return checked;
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedKeys,
        type: this.multiple ? "checkbox" : "radio",
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedKeys = selectedRowKeys;
          this.setSelectedPageRows();
        },
        getCheckboxProps: (record) => ({
          props: {
            disabled: record.isDefault === "Y",
          },
        }),
      };
    },
    // 表格的配置项
    tableColumns() {
      return [
        {
          dataIndex: "defaultName",
          title: () => "默认名称", // 默认名称
          width: 120,
        },
        {
          dataIndex: "customName",
          title: () => "自定义名称", // 自定义名称
          width: 180,
          scopedSlots: { customRender: "tableCustomName" },
        },
        // {
        //   dataIndex: "name",
        //   title: () => "方法名", // 方法名
        //   width: 180,
        // },
        {
          dataIndex: "commentChange",
          sorter: false,
          title: () => "意见", // 意见
          width: 100,
          scopedSlots: { customRender: "tableCommentChange" },
        },
        {
          dataIndex: "sort",
          sorter: false,
          title: () => this.$t("SORT"), // 排序
          width: 100,
        },
      ];
    },
  },
  watch: {
    defaultValue: {
      handler() {
        this.value = undefined;
      },
      immediate: true,
    },
    visible(val) {
      if (val) {
        this.selectedKeys = uniqBy(
          this.selectedKeys.concat(
            this.tableData
              ?.filter((item) => item.isDefault === "Y")
              ?.map((item) => item[this.rowKey])
          )
        );
      }
    },
  },
  methods: {
    handleRowClick(record) {
      const index = this.selectedKeys.findIndex(
        (key) => key === record[this.rowKey]
      );
      if (index > -1) {
        this.selectedKeys.splice(index, 1);
      } else if (this.multiple) {
        this.selectedKeys.push(record[this.rowKey]);
      } else {
        this.selectedKeys = [record[this.rowKey]];
      }
      this.setSelectedPageRows();
    },
    // 打开弹框事件
    openDialog() {
      const selectedKey = this.defaultSelectedRows
        .map((item) => item[this.rowKey])
        .concat(this.defaultSelectedKeys);
      this.selectedKeys = uniqBy([].concat(selectedKey));
      this.value = "";
      this.visible = true;
    },
    /**
     * 获取table的数据
     */
    searchPageData(params) {
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/permission/list-default`, {
          params: {
            type: this.type,
          },
        })
        .then((res) => {
          this.tableData = res.data.data.map((item) => {
            const tmp = this.defaultSelectedRows.find(
              (e) => e[this.rowKey] === item[this.rowKey]
            );
            return {
              ...item,
              customName: tmp?.customName || item.customName || undefined,
              commentIsRequired: item.commentChange === "C",
              commentChange:
                tmp?.needComment || (item.commentChange === "C" ? "N" : "Y"),
            };
          });
          this.selectedKeys = uniqBy(
            this.selectedKeys.concat(
              this.tableData
                .filter((item) => item.isDefault === "Y")
                .map((item) => item[this.rowKey])
            )
          );
          this.setSelectedPageRows();
        });
    },
    // 监听确认按钮事件
    handleConfirm() {
      const newArr = [];
      this.selectedRows.forEach((item) => {
        newArr.push(item.customName || item[this.showKey]);
      });
      this.value = newArr.join();
      this.$emit("confirm", this.selectedKeys, this.selectedRows);
      this.visible = false;
    },
    // 关闭弹框
    closeDialog() {
      this.visible = false;
    },
    // 清空数据
    handleClear() {
      this.value = "";
      this.selectedKeys = [];
      this.$emit("confirm", [], []);
    },
    setSelectedPageRows() {
      if (!this.multiple) {
        Object.keys(this.selectedPageRows).forEach((e) => {
          if (e !== this.page) {
            delete this.selectedPageRows[e];
          }
        });
      }
      this.tableData.forEach((item) => {
        if (this.selectedKeys.includes(item[this.rowKey])) {
          if (this.selectedPageRows[this.page]?.length) {
            !this.selectedPageRows[this.page]
              .map((e) => e[this.rowKey])
              .includes(item[this.rowKey]) &&
              this.selectedPageRows[this.page].push(item);
          } else {
            this.$set(this.selectedPageRows, this.page, [item]);
          }
        } else if (this.selectedPageRows[this.page]?.length) {
          const index = this.selectedPageRows[this.page].findIndex(
            (e) => e[this.rowKey] === item[this.rowKey]
          );
          index > -1 && this.selectedPageRows[this.page].splice(index, 1);
        }
      });
    },
  },
};
</script>
