<template>
  <a-card>
    <yo-table
      :bordered="false"
      :columns="columns"
      :load-data="loadData"
      :row-selection="{ selectedRowKeys: selectedRowKeys, onChange: (e) => selectedRowKeys = e  }"
      @query="onQuery"
      @resetQuery="onResetQuery"
      ref="table"
      size="small"
    >
      <Auth auth="sysDictData:page" slot="query">
        <!-- 此处添加查询表单控件 -->
        <a-form-model-item label="文本">
          <a-input placeholder="请输入文本" v-model="query.value" />
        </a-form-model-item>
        <a-form-model-item label="字典值">
          <a-input placeholder="请输入字典值" v-model="query.code" />
        </a-form-model-item>
      </Auth>
      <Auth auth="sysDictData:delete" slot="operator">
        <a-popconfirm
          :disabled="!selectedRowKeys.length"
          @confirm="onDeleteBatch"
          placement="bottomLeft"
          title="是否确认删除"
        >
          <a-button :disabled="!selectedRowKeys.length">批量删除</a-button>
        </a-popconfirm>
      </Auth>
      <Auth auth="sysDictData:add" slot="footer">
        <a-button @click="onAddRow" block icon="plus">新增字典数据</a-button>
      </Auth>
      <!-- 格式化字段内容 -->
      <Auth auth="sysDictData:edit" slot="value" slot-scope="text, record">
        <a-input placeholder="请输入文本" v-model="record.value" />
      </Auth>
      <Auth auth="sysDictData:edit" slot="code" slot-scope="text, record">
        <a-input placeholder="请输入字典值" v-model="record.code" />
      </Auth>
      <Auth auth="sysDictData:edit" slot="extCode" slot-scope="text, record">
        <a @click="onOpen('ext-code-form', record)" class="json-editor">JSON</a>
      </Auth>
      <Auth auth="sysDictData:edit" slot="sort" slot-scope="text, record">
        <a-input-number
          :min="0"
          :step="1"
          class="w-100-p"
          placeholder="请输入排序"
          v-model="record.sort"
        />
      </Auth>
      <Auth auth="sysDictData:edit" slot="remark" slot-scope="text, record">
        <a-input placeholder="请输入备注" v-model="record.remark" />
      </Auth>

      <span slot="status" slot-scope="text">{{ bindCodeValue(text, 'commonStatus') }}</span>
      <!-- 添加操作控件 -->
      <span slot="action" slot-scope="text, record">
        <yo-table-actions v-if="record.id">
          <Auth auth="sysDictData:edit">
            <a @click="onSaveEdit(record)">保存编辑</a>
          </Auth>
          <Auth auth="sysDictData:delete">
            <a-popconfirm @confirm="onDelete(record)" placement="topRight" title="是否确认删除">
              <a>删除</a>
            </a-popconfirm>
          </Auth>
          <!-- 可在此处添加其他操作控件 -->
        </yo-table-actions>
        <yo-table-actions v-else>
          <Auth auth="sysDictData:add">
            <a @click="onSaveAdd(record)">保存</a>
          </Auth>
          <Auth auth="sysDictData:add">
            <a @click="onDeleteRow(record)">取消</a>
          </Auth>
        </yo-table-actions>
      </span>
    </yo-table>

    <yo-modal-form :title="'编辑'" @ok="onSaveExtCode" ref="ext-code-form">
      <form-body />
    </yo-modal-form>
  </a-card>
</template>
<style lang="less" scoped>
@import (reference) '~@/assets/style/app.less';
.ant-card {
  /deep/.ant-table-footer {
    border-width: 1px 0 0 !important;
    background-color: transparent;
  }
  /deep/.yo-table .ant-table-content .ant-table-body>table>.ant-table-thead>tr>th:last-child,
  /deep/.yo-table .ant-table-content .ant-table-body>table>.ant-table-tbody>tr>td:last-child {
    border-right-width: 0 !important;
  }
  .json-editor {
    font-weight: bold;

    display: inline-block;

    transform: scaleY(.85);

    color: transparent;
    background-image: linear-gradient(135deg, @primary-color, @success-color);
    -webkit-background-clip: text;
  }
}

</style>
<script>
import FormBody from './form';

export default {
  components: {
    FormBody,
  },

  props: {
    type: {
      type: Object,
    },

    codes: {
      type: Object,
    },
  },
  data() {
    return {
      query: {
        typeId: this.type.id,
      },
      columns: [
        {
          title: '文本',
          dataIndex: 'value',
          sorter: true,
          scopedSlots: { customRender: 'value' },
          width: '20%',
        },
        {
          title: '字典值',
          dataIndex: 'code',
          sorter: true,
          scopedSlots: { customRender: 'code' },
          width: '15%',
        },
        {
          title: '扩展值',
          dataIndex: 'extCode',
          scopedSlots: { customRender: 'extCode' },
          width: 100,
          align: 'center',
        },
        {
          title: '排序',
          dataIndex: 'sort',
          sorter: true,
          scopedSlots: { customRender: 'sort' },
          width: '15%',
        },
        {
          title: '备注',
          dataIndex: 'remark',
          sorter: true,
          scopedSlots: { customRender: 'remark' },
        },
        {
          title: '状态',
          dataIndex: 'status',
          scopedSlots: { customRender: 'status' },
          sorter: true,
          width: 80,
        },
      ],

      selectedRowKeys: [],
    };
  },
  created() {
    this.onLoadCodes();

    /** 根据权限添加操作列 */
    const flag = this.$auth({ sysDictData: [['edit'], ['delete']] });
    if (flag) {
      this.columns.push({
        title: '操作',
        width: '150px',
        dataIndex: 'action',
        scopedSlots: { customRender: 'action' },
      });
    }
  },
  methods: {
    /**
     * 必要的方法
     * 传给yo-table以示意数据接口及其参数和返回的数据结构
     */
    loadData(params) {
      return (
        this.$api
          /** !!此处必须修改调用的接口方法 */
          .sysDictDataPage({
            ...params,
            ...this.query,
          })
          .then((res) => {
            return res.data;
          })
      );
    },

    /**
     * 有查询功能时的必要方法
     * 加载数据时初始化分页信息
     */
    onQuery() {
      this.$refs.table.onReloadData(true);
    },

    /**
     * 有查询功能时的必要方法
     * 重置查询条件
     */
    onResetQuery() {
      /** 在这里重置查询条件时,可对特殊的字段做保留处理 */
      Object.keys(this.query).forEach((p) => {
        if (p !== 'typeId') {
          this.query[p] = undefined;
        }
      });
      this.onQuery();
    },

    /**
     * 必要方法
     * 重新列表数据
     */
    onReloadData() {
      this.$refs.table.onReloadData();
    },

    /**
     * 必要方法
     * 加载字典数据
     * 如果不需要获取相应的字典数据,此方法内容可空
     */
    onLoadCodes() {},

    /**
     * 必要方法
     * 绑定数据字典值
     */
    bindCodeValue(code, name) {
      const c = this.codes[name].find((p) => p.code == code);
      if (c) {
        return c.value;
      }
      return null;
    },

    /**
     * 必要方法
     * 从列表页调用窗口的打开方法
     */
    onOpen(formName, record) {
      this.$refs[formName].onOpen({
        typeId: this.type.id,
        record,
      });
    },

    /**
     * 必要方法
     * 可以用做一系列操作的公共回调,此方法中会重新加载当前列表
     */
    onResult(success, successMessage) {
      if (success) {
        this.$message.success(successMessage);
        this.onReloadData();
      }
      this.$refs.table.onLoaded();
    },

    /**
     * 必要方法
     * 删除时调用
     */
    onDelete(record) {
      this.$refs.table.onLoading();
      this.$api
        /** !!此处必须修改调用的接口方法 */
        .sysDictDataDelete(record)
        .then(({ success }) => {
          this.onResult(success, '删除成功');
        });
    },

    onDeleteBatch() {
      this.$refs.table.onLoading();
      this.$api.sysDictDataDeleteBatch(this.selectedRowKeys).then(({ success }) => {
        this.onResult(success, '删除成功');
      });
    },

    onAddRow() {
      this.$refs.table.onAddRow({
        value: '',
        code: '',
        sort: 100,
        typeId: this.query.typeId,
        remark: '',
      });
    },

    onDeleteRow(record) {
      this.$refs.table.onDeleteRow(record);
    },

    onValidate(record) {
      if (!record.value) {
        this.$message.error('请输入字典文本');
        return false;
      }

      if (!record.code) {
        this.$message.error('请输入字典值');
        return false;
      }

      return true;
    },

    onSaveAdd(record) {
      if (this.onValidate(record)) {
        this.$refs.table.onLoading();
        this.$api.sysDictDataAdd(record).then(({ success }) => {
          this.onResult(success, '保存成功');
        });
      }
    },

    onSaveEdit(record) {
      if (this.onValidate(record)) {
        this.$refs.table.onLoading();
        this.$api.sysDictDataEdit(record).then(({ success }) => {
          this.onResult(success, '保存成功');
        });
      }
    },

    onSaveExtCode(record) {
      const data = this.$refs.table.getData().find((p) => p.id === record.id);
      data.extCode = record.extCode;
    },
  },
};
</script>