<template>
  <div>
    <MomTable
      ref="MomTable"
      row-key="id"
      :row-selection="rowSelection"
      :query-param="queryForm"
      :query-param-item="queryFormItem"
      :show-enable-flag="true"
      :columns="tableColumns"
      :data-source="tableData"
      :action-buttons="actionButtons"
      :show-util-operator="true"
      :total="total"
      :page.sync="page"
      :auto-adaptive-width="false"
      @search="searchPageData"
      @beforeSearch="beforeSearch"
      @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('STATION_TERMINAL:ADD')"
          type="primary"
          @click="handleLink()"
        >
          <a-icon type="plus" /> {{ $t("ADD") }}
        </a-button>
        <a-button
          v-if="hasAuth('STATION_TERMINAL:EXPORT')"
          class="btn__green-1"
          icon="to-top"
          :disabled="!tableData.length"
          @click="handleExportExcel"
        >
          {{ $t("EXPORT") }}
        </a-button>
        <a-button
          v-if="hasAuth('STATION_TERMINAL:RELATE')"
          class="btn__blue-6"
          @click="handleRelate"
        >
          <Icon type="icon-edit-block" />
          {{ $t("BULK_ASSOCIATED_PAGES") }}
        </a-button>
        <a-button
          v-if="hasAuth('STATION_TERMINAL:DELETE')"
          type="danger"
          icon="delete"
          @click="() => handleDelete()"
        >
          {{ $t("BATCH_DELETE") }}
        </a-button>
      </div>
      <template slot="enableFlag" slot-scope="text">
        <span :class="text === 'Y' ? 'text-success' : 'text-error'">
          {{ getAttrValue(enableFlagList, text) }}
        </span>
      </template>
    </MomTable>
    <MegaDrawer
      :visible.sync="drawerVisible"
      :title="
        visibleType === 'add'
          ? $t('ADD_TERMINAL')
          : visibleType === 'link'
          ? $t('PUSH_TERMINAL_PAGE')
          : $t('EDIT_TERMINAL')
      "
      width="520"
      @close="close"
    >
      <a-form-model
        v-if="['add', 'edit'].includes(visibleType)"
        slot="main"
        ref="ruleForm"
        layout="vertical"
        :model="ruleForm"
        :rules="rules"
      >
        <a-form-model-item :label="$t('TERMINAL_CODING')" prop="terminalCode">
          <a-input
            v-model="ruleForm.terminalCode"
            :disabled="visibleType === 'edit'"
            :placeholder="$t('PLACEENTER')"
          />
        </a-form-model-item>
        <a-form-model-item :label="$t('TERMINAL_NAME')" prop="terminalName">
          <a-input
            v-model="ruleForm.terminalName"
            :placeholder="$t('PLACEENTER')"
          />
        </a-form-model-item>
        <a-form-model-item :label="$t('REMARK')" prop="remark">
          <a-input
            v-model="ruleForm.remark"
            allow-clear
            :placeholder="$t('PLACEENTER')"
          ></a-input>
        </a-form-model-item>
      </a-form-model>
      <a-form-model
        v-else-if="visibleType === 'link'"
        slot="main"
        ref="ruleForm"
        layout="vertical"
        :model="ruleForm"
      >
        <a-form-model-item :label="$t('TERMINAL_CODING')" prop="terminalCode">
          <a-input
            v-model="ruleForm.terminalCode"
            :placeholder="$t('PLACEENTER')"
            disabled
          />
        </a-form-model-item>
        <a-form-model-item
          :label="$t('TERMINAL_NAME')"
          prop="terminalName"
          :rules="[
            {
              required: true,
              message: $t('PLACEENTER'),
              trigger: 'blur',
            },
          ]"
        >
          <a-input
            v-model="ruleForm.terminalName"
            :placeholder="$t('PLACEENTER')"
            disabled
          />
        </a-form-model-item>
        <a-form-model-item
          :label="$t('SELECT_PAGE_RESOURCES')"
          prop="configType"
        >
          <a-select
            v-model="pageId"
            mode="multiple"
            allow-clear
            show-search
            :filter-option="filterOption"
            :placeholder="$t('PLACESELECT')"
            @change="handleChange"
          >
            <a-select-option
              v-for="item in typeOptions"
              :key="item.value"
              :value="item.value"
              >{{ item.label }}</a-select-option
            >
          </a-select>
        </a-form-model-item>
      </a-form-model>
      <div slot="footer" class="drawer-footer">
        <a-button type="primary" @click="save">
          <Icon type="icon-cur-save_1" :size="18" /> {{ $t("SAVE") }}
        </a-button>
        <a-button @click="close">
          <Icon type="icon-dir-f-rollback" :size="18" /> {{ $t("CANCEL") }}
        </a-button>
      </div>
    </MegaDrawer>
    <!-- <SelectCp /> -->
  </div>
</template>
<script>
import { Drawer as MegaDrawer, Icon } from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";
import { exportExcel } from "@/utils";
// import SelectCp from "@/components/SelectCp/index.vue";

export default {
  components: {
    MegaDrawer,
    Icon,
    // SelectCp,
  },
  data() {
    return {
      editId: "",
      enableFlagList: [],
      pageId: [],
      confirmLoading: false,
      loading: false,
      typeOptions: [],
      stationOptions: [],
      queryForm: {
        terminalCode: "",
        terminalName: "",
      },
      tableData: [],
      page: 1, // 页码
      total: 0,
      actionButtons: [
        (h, { record }) =>
          this.hasAuth("STATION_TERMINAL:EDIT") && (
            <span
              class="text-primary cursor-pointer"
              title={this.$t("MODIFY")}
              onClick={() => this.handleLink(record, "edit")}>
              <Icon type="icon-edit-edit" />
            </span>
          ),
        (h, { record }) =>
          this.hasAuth("STATION_TERMINAL:LINK") && (
            <span
              class="text-primary cursor-pointer"
              title={this.$t("LINK_PAGE")}
              onClick={() => this.handleLink(record, "link")}>
              <Icon type="icon-edit-block" />
            </span>
          ),

        (h, { record }) =>
          this.hasAuth("STATION_TERMINAL:DELETE") && (
            <span
              class="text-error cursor-pointer"
              title={this.$t("DELETE")}
              onClick={() => this.handleDelete(record)}>
              <Icon type="icon-edit-delete" />
            </span>
          ),
      ],
      selectedRowKeys: [],
      flag: "",

      visibleType: "",
      drawerVisible: false,
      ruleForm: {
        terminalCode: undefined,
        terminalName: undefined,
        facStationId: undefined,
        remark: undefined,
      },
    };
  },
  computed: {
    queryFormItem() {
      return this.$observable("queryFormItem", {
        terminalCode: {
          label: () => this.$t("TERMINAL_CODING"), // 终端编码
        },
        terminalName: {
          label: () => this.$t("TERMINAL_NAME"), // 终端名称
        },
      });
    },
    rowSelection() {
      return {
        selectedRowKeys: this.selectedRowKeys,
        onChange: (selectedRowKeys, selectedRows) => {
          this.selectedRowKeys = selectedRowKeys;
        },
      };
    },
    tableColumns() {
      return this.$observable("tableColumns", [
        {
          dataIndex: "terminalCode",
          width: 200,
          sorter: false,
          ellipsis: true,
          title: () => this.$t("TERMINAL_CODING"), // 终端编码
        },
        {
          dataIndex: "terminalName",
          width: 200,
          ellipsis: true,
          sorter: false,
          title: () => this.$t("TERMINAL_NAME"), // 终端名称
        },
        // {
        //   dataIndex: "pageName",
        //   width: 200,
        //   sorter: false,
        //   ellipsis: true,
        //   title: () => this.$t("LINK_PAGE"), // 关联页面
        // },
        {
          dataIndex: "remark",
          sorter: false,
          ellipsis: true,
          title: () => this.$t("REMARK"), // 备注
        },
        {
          dataIndex: "enableFlag",
          width: 120,
          sorter: false,
          ellipsis: true,
          title: () => this.$t("STATUS"), // 状态
          scopedSlots: { customRender: "enableFlag" },
        },
        {
          dataIndex: "updateBy",
          title: () => this.$t("UPDATE_BY"),
          width: 120,
          sorter: false,
        },
        {
          dataIndex: "updateTime",
          title: () => this.$t("UPDATE_TIME"),
          width: 168,
        },
      ]);
    },
    rules() {
      return {
        terminalCode: [this.validateFieldLength(0, 16)],
        terminalName: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
          this.validateFieldLength(1, 50),
        ],
        remark: [this.validateFieldLength(0, 16)],
      };
    },
  },
  methods: {
    filterOption(input, option) {
      return option.componentOptions.children[0].text
        .toLowerCase()
        .includes(input.toLowerCase());
    },
    beforeSearch() {
      this.getDictByCode("DIC:COMMON:ENABLE_FLAG").then((res) => {
        this.enableFlagList = res?.data?.data || [];
      });
    },
    // 启用、禁用
    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/ideterminal/enable/${id}/${status}`
            )
            .then((res) => {
              this.$message.success(this.$t(tips));
              this.$refs.MomTable?.query();
            });
        },
      });
    },
    handleExportExcel() {
      const params = {
        page: this.page,
        size: this.$store.state.pagination.pageSize,
        ...this.queryForm,
      };
      this.$axios({
        url: `${ApiConstant.PREFIX_CORE}/api/ideterminal/export`,
        method: "get",
        params,
        responseType: "blob",
      }).then((res) => {
        exportExcel(res.data, `${this.$t("LOCATION_OF_TERMINAL")}.xls`);
      });
    },

    searchPageData(params) {
      const p = {
        ...params,
        ...this.queryForm,
      };
      this.loading = true;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/ideterminal/search`, {
          params: p,
        })
        .then((res) => {
          const { records, total } = res.data.data;
          this.total = total;
          this.tableData = records;
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    async handleLink(r, q) {
      if (r && q === "link") {
        await this.getTypeOptionList();
        await this.getStationList(r.id);
        this.editId = r.id;
        this.drawerVisible = true;
        this.visibleType = "link";
        this.flag = "link";
      } else if (r && q === "edit") {
        this.getOptions();
        this.getStationList(r.id);
        this.flag = "edit";
        this.visibleType = "edit";
        this.drawerVisible = true;
      } else {
        this.getOptions();
        this.visibleType = "add";
        this.flag = "add";
        this.drawerVisible = true;
      }
    },
    getOptions() {
      this.loading = true;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/mdm/fac-station/list-search-key`)
        .then((res) => {
          const { data } = res.data;
          this.stationOptions = data.map((item) => {
            return {
              label: item.stationName,
              value: item.id,
            };
          });
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    getTypeOptionList() {
      this.loading = true;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/idewebpage/list-search-key`, {
          params: { enableFlag: "Y" },
        })
        .then((res) => {
          const { data } = res.data;
          this.typeOptions = data.map((item) => {
            return {
              label: item.pageName,
              value: item.id,
            };
          });
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    getStationList(id) {
      this.loading = true;
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/ideterminal/get-by-id/${id}`)
        .then((res) => {
          const { data } = res.data;
          this.ruleForm = data;
          this.pageId = data.pageId ? data.pageId.split(",") : [];
          this.loading = false;
        })
        .catch(() => {
          this.loading = false;
        });
    },
    save() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (this.flag === "add") {
            this.confirmLoading = true;
            const p = { ...this.ruleForm };
            this.$axios
              .post(`${ApiConstant.PREFIX_CORE}/api/ideterminal`, p)
              .then(() => {
                this.$message.success(this.$t("ADD_SUCCESS"));
                this.close();
                this.$refs.MomTable?.query();
                this.confirmLoading = false;
              })
              .catch(() => {
                this.confirmLoading = false;
              });
          } else if (this.flag === "link") {
            this.confirmLoading = true;
            const p = {
              pageCodeList: this.pageId,
              id: this.editId,
              ...this.ruleForm,
            };
            this.$axios
              .put(`${ApiConstant.PREFIX_CORE}/api/ideterminal/update-page`, p)
              .then(() => {
                this.$message.success(this.$t("EDIT_SUCCESS"));
                this.close();
                this.$refs.MomTable?.query();
                this.confirmLoading = false;
              })
              .catch(() => {
                this.confirmLoading = false;
              });
          } else if (this.flag === "edit") {
            this.confirmLoading = true;
            const p = { id: this.editId, ...this.ruleForm };
            this.$axios
              .put(`${ApiConstant.PREFIX_CORE}/api/ideterminal`, p)
              .then(() => {
                this.$message.success(this.$t("EDIT_SUCCESS"));
                this.close();
                this.$refs.MomTable?.query();
                this.confirmLoading = false;
              })
              .catch(() => {
                this.confirmLoading = false;
              });
          }
        }
      });
    },
    close() {
      this.ruleForm.remark = undefined;
      this.ruleForm.facStationId = undefined;
      this.ruleForm.terminalName = undefined;
      this.ruleForm.terminalCode = undefined;
      this.pageId = undefined;
      this.drawerVisible = false;
    },
    handleDelete(r) {
      if (r || 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: () => {
            if (r) {
              this.$axios
                .delete(`${ApiConstant.PREFIX_CORE}/api/ideterminal/${r.id}`)
                .then(() => {
                  this.$message.success(this.$t("DELETE_SUCCESS"));
                  this.$refs.MomTable?.query();
                });
            } else {
              this.$axios
                .delete(
                  `${ApiConstant.PREFIX_CORE}/api/ideterminal/batch-delete`,
                  { params: { ids: this.selectedRowKeys.join(",") } }
                )
                .then(() => {
                  this.$message.success(this.$t("DELETE_SUCCESS"));
                  this.selectedRowKeys = [];
                  this.$refs.MomTable?.query();
                });
            }
          },
        });
      } else {
        this.$message.error(this.$t("SELECT_ONE_DATA"));
      }
    },
    handleChange() {},
    // 批量关联页面
    handleRelate() {
      this.$router.push({
        path: "/upms/devCenter/station/relate",
      });
    },
  },
};
</script>
