<template>
  <div>
    <a-button style="margin-bottom:20px;" @click="toBack">{{ $lang('返回') }}</a-button>
    <search-table ref="table"
                  :searchItems="searchItems"
                  :tableTitle="'公共字典 - '+detailItem.typeName"
                  :tableRowKey="'dictId'"
                  :tableColumns="columns"
                  :tableRemoteUrl="remoteUrl"
                  :tableRemoteParams="remoteData"
                  :tableExtraBtns="tableEtraBtns"
                  :tableOperators="tableOperators">

      <template v-slot:isEnable="{record}">
        <SwitchValue :value="record.isEnable" @change="checkedChange($event,record)"/>
      </template>
    </search-table>
    <a-modal :title="$lang('公共字典')" v-model="isShowModal" :confirm-loading="confirmLoading" @ok="handleOk"
             @cancel="handleCancel">

      <p-grid-form ref="editorForm" :span="24" :items="formItems"/>
      <div v-show="error" style="margin-top:20px;color:red;">
        <p>{{ error }}</p>
      </div>
    </a-modal>

  </div>
</template>

<script>
import SearchTable from "../../components/search-table";
import {dictSearchItems} from "./config/searchItems";
import {dictColumns} from "./config/columns";
import {dictFormItems} from "./config/formItems";
import {api as dictApi, addItem, uploadItem, deleteList} from "./api/dictionaries";

export default {

  components: {
    'search-table': SearchTable
  },

  props: ['detailItem'],

  data() {
    return {
      searchItems: dictSearchItems,
      columns: dictColumns,
      data: null,
      selectedRowKeys: [],

      remoteUrl: dictApi.queryList,
      remoteData: {
        dicttypeId: this.detailItem.typeId
      },
      isShowModal: false,
      selectedItem: null,
      formItems: dictFormItems,
      confirmLoading: false,
      error: '',

      tableEtraBtns: [
        {
          label: '新增', click: () => {
            this.showModal()
          }
        },
        {
          label: '批量删除', click: () => {
            this.deleteList()
          }
        }
      ],
      tableOperators: [
        {
          label: '修改', click: (record) => {
            this.uploadItem(record)
          }
        },
        {
          label: '删除', click: (record) => {
            this.deleteItem(record)
          }
        },
      ],

    }
  },

  methods: {

    toBack() {
      this.$emit('changeStep', {step: 1, item: null});
    },

    checkedChange(checked, item) {
      let p = {};
      item.isEnable = checked;
      this.formItems.forEach(t => {
        Reflect.has(item, t.name) ? p[t.name] = item[t.name] : null;
      });
      p.dictId = item.dictId;
      this.handleUploadItem(p);
    },

    uploadItem(item) {
      this.selectedItem = item;
      if (!item.dictDesc) item.dictDesc = '';
      this.showModal();
      this.$nextTick(() => {
        this.$refs.editorForm.form.disableItem('dictCode')
        this.$refs.editorForm.form.setFieldsValue(item);
      });
    },

    deleteItem(item) {
      this.$confirm({
        content: this.$lang('是否删除选中项?'),
        onOk: () => {
          return this.handleDelete(item.dictId);
        }
      });
    },

    deleteList() {
      let list = this.$refs.table.getSelectedItem();
      if (list.length == 0) {
        this.$message.error(this.$lang('请选择要删除的项'));
        return;
      }
      let ids = [];
      list.forEach(t => ids.push(t.dictId));
      this.$confirm({
        content: this.$lang('是否删除选中项?'),
        onOk: () => {
          return this.handleDelete(ids.join(','));
        }
      });
    },

    showModal() {
      this.isShowModal = true;
      this.$nextTick(() => {
        this.$refs.editorForm.form.enableItem('dictCode')
      })
    },

    handleOk() {
      this.$refs.editorForm.form.validateFields((errs, vals) => {
        if (errs) {
          return;
        }
        if (this.selectedItem) {
          vals.dictId = this.selectedItem.dictId;
          this.handleUploadItem(vals);
        } else {
          this.handleAddItem(vals);
        }
      });
    },

    handleCancel() {
      this.isShowModal = false;
      this.selectedItem = null;
      if (this.$refs.editorForm) this.$refs.editorForm.form.resetFields();
    },

    handleAddItem(params) {
      this.confirmLoading = true;
      return addItem({...params, dicttypeId: this.detailItem.typeId}).then(res => {
        this.confirmLoading = false;
        if (!res.success) {
          this.$exception(res);
          return;
        }
        this.$refs.table.reload();
        this.$message.success(this.$lang('新增成功'));
        this.handleCancel();
      });
    },

    handleUploadItem(params) {
      this.confirmLoading = true;
      return uploadItem({...params, dicttypeId: this.detailItem.typeId}).then(res => {
        this.confirmLoading = false;
        if (!res.success) {
          this.$exception(res);
          return;
        }
        this.$refs.table.reload();
        this.$message.success(this.$lang('修改成功'));
        this.handleCancel();
      });
    },

    handleDelete(ids) {
      return deleteList({ids: ids}).then(res => {
        if (!res.success) {
          this.$exception(res);
          return;
        }
        this.$refs.table.reload();
        this.$message.success(this.$lang('删除成功'));
      });
    },

  }

}
</script>

<style>
</style>