<template>
  <div class="dictionary">
    <a-select v-model="dictionary" style="width: 120px" @change="handChange">
      <div slot="dropdownRender" slot-scope="menu">
        <v-nodes :vnodes="menu" />
        <a-divider style="margin: 4px 0" />
        <div
          class="selectAdd"
          @mousedown="(e) => e.preventDefault()"
          @click="addItem"
        >
          <a-icon type="plus" style="margin: 3px 5px 0 0" /> {{ $t("ADD") }}
        </div>
      </div>
      <a-select-option
        v-for="item in items"
        :key="item.value"
        :value="item.value"
      >
        {{ item.label }}
      </a-select-option>
    </a-select>
    <MegaModal
      class="dictDialog app"
      :title="$t('DICTIONARY')"
      width="60%"
      :visible="isDictionary"
      @cancel="saveCancel"
      @close="saveCancel"
    >
      <a-collapse
        v-model="activeName"
        :bordered="false"
        expand-icon-position="right"
        class="collapse-header-divide"
      >
        <a-collapse-panel key="a" :header="$t('BASE_INFO')">
          <a-form-model
            ref="detailForm"
            layout="vertical"
            :model="detailForm"
            :label-col="{ span: 6 }"
            :wrapper-col="{ span: 18 }"
          >
            <a-row style="padding: 0 20px">
              <a-col :span="6">
                <a-form-model-item prop="dictCode" :label="`${$t('CODE')}:`">
                  <a-input v-model="detailForm.dictCode" disabled />
                </a-form-model-item>
              </a-col>
              <a-col :span="6">
                <a-form-model-item prop="dictName" :label="`${$t('NAME')}:`">
                  <a-input v-model="detailForm.dictName" disabled />
                </a-form-model-item>
              </a-col>
            </a-row>
          </a-form-model>
        </a-collapse-panel>
      </a-collapse>
      <a-collapse
        v-model="activeNameB"
        :bordered="false"
        expand-icon-position="right"
        class="collapse-header-divide"
      >
        <a-collapse-panel key="b" :header="$t('DICTIONARY_ITEM')">
          <MomTable
            row-key="id"
            :columns="tableColumns"
            :data-source="detailForm.dictionaryData"
            :action-buttons="tableAction"
            :pagination="false"
            @edit="editChildDict"
            @delete="delChildDict"
          >
            <template slot="enableFlag" slot-scope="text">
              <span :class="text === 'Y' ? 'text-success' : 'text-error'">
                {{ getAttrValue(enableFlagList, text) }}
              </span>
            </template>
            <div slot="toolbar">
              <a-button
                v-if="hasAuth('DICTIONARY_MANAGEMENT:ADD')"
                class="fr"
                type="success"
                :disabled="dictionaryCode === ''"
                @click="addChildDict"
              >
                <a-icon type="plus" />
                {{ $t("ADD") }}
              </a-button>
            </div>
          </MomTable>
        </a-collapse-panel>
      </a-collapse>
      <div slot="footer"></div>
    </MegaModal>
    <MegaDrawer
      :title="title"
      :visible.sync="drawer"
      width="520"
      @close="drawerClose"
    >
      <template slot="main">
        <a-form-model
          ref="dictChildForm"
          layout="vertical"
          :model="dictChildForm"
          :rules="dictChildFormRules"
        >
          <a-form-model-item :label="$t('NAME')" prop="dataLabel">
            <a-input
              v-model.trim="dictChildForm.dataLabel"
              :placeholder="$t('PLACEENTER')"
              allow-clear
            />
          </a-form-model-item>
          <a-form-model-item :label="$t('DATA_VALUE')" prop="dataValue">
            <a-input
              v-model.trim="dictChildForm.dataValue"
              :placeholder="$t('PLACEENTER')"
              allow-clear
            />
          </a-form-model-item>
          <a-form-model-item :label="$t('STATUS')" prop="enableFlag">
            <a-select
              v-model="dictChildForm.enableFlag"
              :placeholder="$t('PLACESELECT')"
            >
              <a-select-option
                v-for="item in enableFlagList"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item :label="$t('SORT')" prop="dataOrder">
            <a-input-number
              v-model="dictChildForm.dataOrder"
              :min="0"
              style="width: 100%"
            />
          </a-form-model-item>
          <a-form-model-item :label="$t('CATEGORY')" prop="dataCategory">
            <a-select
              v-model="dictChildForm.dataCategory"
              :placeholder="$t('PLACESELECT')"
            >
              <a-select-option
                v-for="item in dictCategoryList"
                :key="item.value"
                :value="item.value"
              >
                {{ item.label }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
          <a-form-model-item
            :label="$t('EXTENDED_FIELD') + '1'"
            prop="dataValueExt1"
          >
            <a-textarea
              v-model.trim="dictChildForm.dataValueExt1"
              :placeholder="$t('PLACEENTER')"
              type="textarea"
              :auto-size="{ minRows: 2 }"
            />
          </a-form-model-item>
          <a-form-model-item
            :label="$t('EXTENDED_FIELD') + '2'"
            prop="dataValueExt2"
          >
            <a-textarea
              v-model.trim="dictChildForm.dataValueExt2"
              :placeholder="$t('PLACEENTER')"
              type="textarea"
              :auto-size="{ minRows: 2 }"
            />
          </a-form-model-item>
          <a-form-model-item :label="$t('REMARK')" prop="remark">
            <a-textarea
              v-model.trim="dictChildForm.remark"
              :placeholder="$t('PLACEENTER')"
              type="textarea"
              :auto-size="{ minRows: 2 }"
            />
          </a-form-model-item>
        </a-form-model>
      </template>
      <footer slot="footer">
        <a-button type="primary" @click="confirm">
          <Icon type="icon-cur-save_1" :size="18" /> {{ $t("SAVE") }}
        </a-button>
        <a-button @click="cancel">
          <Icon type="icon-dir-f-rollback" :size="18" />{{ $t("CANCEL") }}
        </a-button>
      </footer>
    </MegaDrawer>
  </div>
</template>
<script>
import {
  Modal as MegaModal,
  Drawer as MegaDrawer,
  Icon,
} from "@mega-design/ui-vue";
import ApiConstant from "@/api/ApiConstant";

export default {
  components: {
    MegaModal,
    MegaDrawer,
    Icon,
    VNodes: {
      functional: true,
      render: (h, ctx) => ctx.props.vnodes,
    },
  },
  props: {
    // 需要展示的key
    dictionaryCode: {
      type: String,
      default: "",
    },
  },
  data() {
    return {
      activeName: "a",
      activeNameB: "b",
      dictionary: "",
      title: this.$t("ADD"),
      isDictionary: false,
      drawer: false,
      items: ["jack", "lucy"],
      enableFlagList: [],
      dictCategoryList: [],
      dictChildForm: {
        dictCode: this.dictionaryCode,
        parentDictCode: "",
        dataLabel: "",
        dataValue: "",
        enableFlag: "Y",
        dataOrder: "",
        dataValueExt1: "",
        dataValueExt2: "",
        remark: "",
        dataCategory: "",
      },
      detailForm: {
        dictName: "",
        dictCode: "",
      },
      id: "",
      tableAction: [
        this.hasAuth("DICTIONARY_MANAGEMENT:EDIT") && "edit",
        (h, value, a, b) => {
          if (this.hasAuth("DICTIONARY_MANAGEMENT:ENABLED")) {
            return (
              <span type="text">
                {value.record.enableFlag === "Y" ? (
                  <Icon
                    onClick={() => this.disableChildDict(value.record, "N")}
                    type="icon-ins-stop"
                    size={15}
                    style="color: #d45f5f; cursor: pointer"
                    title={this.$t("DISABLED")}
                  />
                ) : (
                  <Icon
                    onClick={() => this.disableChildDict(value.record, "Y")}
                    type="icon-ins-check-circle"
                    size={15}
                    style="color: #0ea8d0; cursor: pointer"
                    title={this.$t("ENABLED")}
                  />
                )}
              </span>
            );
          }
          return null;
        },
        this.hasAuth("DICTIONARY_MANAGEMENT:DELETE") && "delete",
      ],
    };
  },
  computed: {
    dictChildFormRules() {
      // eslint-disable-next-line
      const temp_obj = {
        dataLabel: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
          {
            max: 32,
            message: this.$t("PLACEENTER") + 32 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        dataValue: [
          {
            required: true,
            message: this.$t("PLACEENTER"),
            trigger: "blur",
          },
          {
            max: 32,
            message: this.$t("PLACEENTER") + 32 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
        dataOrder: [],
        dataCategory: [],
        remark: [
          {
            max: 255,
            message: this.$t("PLACEENTER") + 255 + this.$t("LENGTH_TIP"),
            trigger: "blur",
          },
        ],
      };
      // eslint-disable-next-line
      return temp_obj;
    },
    tableColumns() {
      return [
        {
          dataIndex: "dataLabel",
          title: () => this.$t("NAME"),
          width: 160,
          sorter: false,
        },
        {
          dataIndex: "dataValue",
          title: () => this.$t("DATA_VALUE"),
          width: 280,
          sorter: false,
        },
        {
          dataIndex: "enableFlag",
          key: "enableFlag",
          title: () => this.$t("STATUS"),
          scopedSlots: { customRender: "enableFlag" },
          width: 100,
          sorter: false,
        },
        {
          dataIndex: "dataOrder",
          title: () => this.$t("SORT"),
          width: 80,
          sorter: false,
        },
        {
          dataIndex: "remark",
          title: () => this.$t("REMARK"),
          width: 200,
          sorter: false,
        },
        {
          dataIndex: "updateBy",
          title: () => this.$t("UPDATE_BY"),
          width: 120,
          sorter: false,
        },
        {
          dataIndex: "updateTime",
          title: () => this.$t("UPDATE_TIME"),
          minWidth: 200,
          sorter: false,
        },
      ];
    },
  },
  mounted() {
    Promise.all([
      this.getDictByCode(this.dictionaryCode),
      this.getDictByCode("DIC:CORE:DIC_CATEGORY"),
      this.getDictByCode("DIC:EPM:ENABLE_STATUS"),
    ]).then(([res, dicRes, enableRes]) => {
      this.items = res.data.data;
      this.dictCategoryList = dicRes.data.data;
      this.enableFlagList = enableRes.data.data;
    });
    this.getData();
  },
  methods: {
    getData() {
      this.$axios
        .get(
          `${ApiConstant.PREFIX_CORE}/api/sys/dict/get-detail/${this.dictionaryCode}`
        )
        .then((res) => {
          this.detailForm = res.data.data;
        });
    },
    addItem() {
      this.isDictionary = true;
    },
    confirm() {
      this.$refs.dictChildForm.validate((valid) => {
        if (valid) {
          if (this.title === this.$t("EDIT")) {
            this.$axios
              .put(`${ApiConstant.PREFIX_CORE}/api/sys/dict-data`, {
                ...this.dictChildForm,
                id: this.id,
              })
              .then((res) => {
                this.drawer = false;
                this.$message.success(this.$t("EDIT_SUCCESS"));
                this.getData();
              });
          } else {
            this.$axios
              .post(
                `${ApiConstant.PREFIX_CORE}/api/sys/dict-data`,
                this.dictChildForm
              )
              .then((res) => {
                this.drawer = false;
                this.$message.success(this.$t("ADD_SUCCESS"));
                this.getData();
              });
          }
        }
      });
    },
    handChange(val) {
      this.$emit("confirm", val);
    },
    // 关闭
    drawerClose() {
      this.$refs.dictChildForm.resetFields();
      this.cancel();
    },
    addChildDict() {
      this.drawer = true;
      this.title = this.$t("ADD");
    },
    // 取消
    cancel() {
      this.drawer = false;
    },
    saveCancel() {
      this.isDictionary = false;
    },
    // 子字典（右侧数据）
    disableChildDict(row, state) {
      let title = "";
      let content = "";
      if (state === "N") {
        content = this.$t("DISABLED_DATA_INFO");
        title = this.$t("DISABLED");
      } else {
        content = this.$t("ENABLED_DATA_INFO");
        title = this.$t("ENABLED");
      }
      this.$confirm({
        title,
        content,
        okType: "warning",
        okText: this.$t("CONFIRM"),
        cancelText: this.$t("CANCEL"),
        centered: false,
        icon: "exclamation-circle",
        onOk: () => {
          this.$axios
            .put(
              `${ApiConstant.PREFIX_CORE}/api/sys/dict-data/enable/${row.id}/${state}`
            )
            .then(() => {
              if (state === "N") {
                this.$message.success(this.$t("DISABLE_SUCCESS"));
              } else {
                this.$message.success(this.$t("ENABLE_SUCCESS"));
              }
              this.getData();
            });
        },
      });
    },
    // 编辑子字典（右侧数据）
    editChildDict(row) {
      // 普通用户不能编辑系统类型的字典
      if (this.dictCategory === "S" && this.user?.mgrType === "USER") {
        this.$message.error(this.$t("EDITDELNOJURISDICTION"));
        return;
      }
      this.drawer = true;
      this.title = this.$t("EDIT");
      this.$axios
        .get(`${ApiConstant.PREFIX_CORE}/api/sys/dict-data/get-by-id/${row.id}`)
        .then((res) => {
          const { data } = res.data;
          this.id = data.id;
          this.dictChildForm.dictCode = data.dictCode;
          this.dictChildForm.dataLabel = data.dataLabel;
          this.dictChildForm.dataValue = data.dataValue;
          this.dictChildForm.enableFlag = data.enableFlag;
          this.dictChildForm.dataOrder = data.dataOrder;
          this.dictChildForm.dataValueExt1 = data.dataValueExt1;
          this.dictChildForm.dataValueExt2 = data.dataValueExt2;
          this.dictChildForm.remark = data.remark;
          this.dictChildForm.dataCategory = data.dataCategory;
        });
    },
    // 删除子字典（右侧数据）
    async delChildDict(row) {
      // 普通用户不能删除系统类型的字典
      if (this.dictCategory === "S" && this.user?.mgrType === "USER") {
        this.$message.error(this.$t("EDITDELNOJURISDICTION"));
        return;
      }
      await 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/sys/dict-data/${row.id}`)
            .then(() => {
              this.$message.success(this.$t("SUBMITTED_FOR_DELETION"));
              this.getData();
            });
        },
      });
    },
  },
};
</script>
<style lang="less" scoped>
.dictDialog {
  /deep/.ant-row {
    display: flex;
    align-items: center;
  }
  /deep/.ant-form-item-label {
    text-align: right !important;
  }
}
</style>
<style lang="less">
.selectAdd {
  padding: 4px 8px;
  cursor: pointer;
  display: flex;
  justify-content: center;
  height: 32px;
  color: #005583;
}
</style>
