<template>
  <basic-container>
    <avue-crud :option="optionParent" :table-loading="loading" :data="dataParent" :page="pageParent" ref="crud"
      v-model="formParent" :permission="permissionList" :before-open="beforeOpen" @row-del="rowDel"
      @row-update="rowUpdate" @row-save="rowSave" @search-change="searchChange" @search-reset="searchReset"
      @selection-change="selectionChange" @current-change="currentChange" @size-change="sizeChange"
      @refresh-change="refreshChange" @on-load="onLoadParent">
      <template #menu-left>
        <el-button type="danger" icon="el-icon-delete" v-if="permission.system_autocode_index_delete" plain
          @click="handleDelete">删 除
        </el-button>
      </template>
      <template #menu="scope">
        <el-button type="primary" text icon="el-icon-setting" @click.stop="handleRowClick(scope.row)">组成配置
        </el-button>
      </template>
      <template #code="{ row }">
        <el-tag @click="handleRowClick(row)" style="cursor: pointer">{{ row.code }}</el-tag>
      </template>
    </avue-crud>
    <el-dialog :title="`[${dictValue}]规则组成`" append-to-body v-model="box" width="1000px">
      <avue-crud :option="optionChild" :table-loading="loadingChild" :data="dataChild" ref="crudChild"
        v-model="formChild" :permission="permissionList" :before-open="beforeOpenChild" :before-close="beforeCloseChild"
        @row-del="rowDelChild" @row-update="rowUpdateChild" @row-save="rowSaveChild" @search-change="searchChangeChild"
        @search-reset="searchResetChild" @selection-change="selectionChangeChild" @current-change="currentChangeChild"
        @size-change="sizeChangeChild" @refresh-change="refreshChangeChild" @on-load="onLoadChild">
        <template #menu-left>
          <el-button type="danger" icon="el-icon-delete" v-if="permission.system_autocode_index_delete" plain
            @click="handleDelete">删 除
          </el-button>
        </template>
        <template #isSealed="{ row }">
          <el-tag>{{ row.isSealed === 0 ? '否' : '是' }}</el-tag>
        </template>
      </avue-crud>
    </el-dialog>
  </basic-container>
</template>

<script>
  import {
    getParentList,
    getChildList,
    remove,
    update,
    add,
    getRule,
    getPart, updatePart, addPart, removePart
  } from '@/api/system/autocode/rule';
  import { mapGetters } from 'vuex';

  export default {
    data() {
      return {
        dictValue: '暂无',
        ruleId: -1,
        formParent: {},
        formChild: {},
        selectionList: [],
        query: {},
        box: false,
        loading: true,
        loadingChild: true,
        pageParent: {
          pageSize: 10,
          pageSizes: [10, 30, 50, 100, 200],
          currentPage: 1,
          total: 0,
        },
        pageChild: {
          pageSize: 10,
          pageSizes: [10, 30, 50, 100, 200],
          currentPage: 1,
          total: 0,
        },
        dataParent: [],
        dataChild: [],
        optionParent: {
          height: 'auto',
          calcHeight: 32,
          tip: false,
          searchShow: true,
          searchMenuSpan: 10,
          border: true,
          index: true,
          selection: true,
          viewBtn: true,
          menuWidth: 350,
          dialogWidth: 650,
          dialogClickModal: false,
          column: [
            {
              label: '规则编号',
              prop: 'ruleCode',
              search: true,
              span: 24,
              rules: [
                {
                  required: true,
                  message: '请输入规则编号',
                  trigger: 'blur',
                },
              ],
            },
            {
              label: '规则名称',
              prop: 'ruleName',
              search: true,
              align: 'center',
              span: 24,
              rules: [
                {
                  required: true,
                  message: '请输入规则名称',
                  trigger: 'blur',
                },
              ],
            },
            {
              label: '描述',
              prop: 'ruleDesc',
              align: 'center',
              span: 24,
              rules: [
                {
                  required: true,
                  message: '请输入描述信息',
                  trigger: 'blur',
                },
              ],
            },
            {
              label: '最大长度',
              prop: 'maxLength',
              type: 'number',
              align: 'right',
              span: 24,
              width: 100,
              rules: [
                {
                  required: true,
                  message: '请输入最大长度',
                  trigger: 'blur',
                },
              ],
            },
            {
              label: '是否补齐',
              prop: 'isPadded',
              type: 'radio',
              width: 100,
              props: {
                min: 1, // 设置最小值
                max: 64, // 设置最大值
              },
              span: 24,
              dicData: [
                {
                  label: '是',
                  value: 'Y',
                },
                {
                  label: '否',
                  value: 'N',
                },
              ],
              value: 'N',
              rules: [
                {
                  required: true,
                  message: '请选择是否补齐',
                  trigger: 'blur',
                },
              ],
              control: (val, form) => {
                if (val === 'Y') {
                  return {
                    paddedChar: {
                      display: true
                    },
                    paddedMethod: {
                      display: true
                    }
                  }
                } else {
                  return {
                    paddedChar: {
                      display: false
                    },
                    paddedMethod: {
                      display: false
                    }
                  }
                }
              },
            },
            {
              label: '补齐字符',
              prop: 'paddedChar',
              span: 24,
              hide: true,
            },
            {
              label: '补齐方式',
              prop: 'paddedMethod',
              type: 'radio',
              width: 100,
              span: 24,
              hide: true,
              dicData: [
                {
                  label: '左补齐',
                  value: 'L',
                },
                {
                  label: '右补齐',
                  value: 'R',
                },
              ],
              rules: [
                {
                  required: true,
                  message: '请选择补齐方式',
                  trigger: 'blur',
                },
              ],
            },
            {
              label: '是否启用',
              prop: 'enableFlag',
              type: 'radio',
              width: 100,
              value: 'Y',
              span: 24,
              dicData: [
                {
                  label: '是',
                  value: 'Y',
                },
                {
                  label: '否',
                  value: 'N',
                },
              ],
              rules: [
                {
                  required: true,
                  message: '请选择是否启用',
                  trigger: 'blur',
                },
              ],
            },
            {
              label: '备注',
              prop: 'remark',
              type: 'textarea',
              span: 24,
            },
          ],
        },
        optionChild: {
          height: 'auto',
          calcHeight: 95,
          tip: false,
          searchShow: true,
          searchMenuSpan: 10,
          tree: true,
          border: true,
          index: true,
          selection: true,
          viewBtn: true,
          menuWidth: 300,
          dialogWidth: 880,
          dialogClickModal: false,
          column: [
            {
              label: '组成编码',
              prop: 'partCode',
              search: true,
              span: 12,
              rules: [
                {
                  required: true,
                  message: '请输入组成编码',
                  trigger: 'blur',
                },
              ],
            },
            {
              label: '组成名称',
              prop: 'partName',
              search: true,
              align: 'center',
              rules: [
                {
                  required: true,
                  message: '请输入组成名称',
                  trigger: 'blur',
                },
              ],
            },
            {
              label: '分段序号',
              prop: 'partIndex',
              rules: [
                {
                  required: false,
                  message: '请选择分段序号',
                  trigger: 'click',
                },
              ],
            },
            {
              label: '分段长度',
              prop: 'partLength',
              type: 'number',
              align: 'right',
              hide: true,
              rules: [
                {
                  required: true,
                  message: '请输入字典排序',
                  trigger: 'blur',
                },
              ],
            },
            {
              label: '分段类型',
              prop: 'partType',
              type: 'select',
              width: 85,
              dicUrl: '/blade-system/dict/dictionary?code=sys_autocode_parttype',
              props: {
                label: 'dictValue',
                value: 'dictKey',
              },
              rules: [
                {
                  required: true,
                  message: '请输入分段类型',
                  trigger: 'blur',
                },
              ],
              control: (val, form) => {
                if (val === 'NOWDATE') {
                  return {
                    dateFormat: { display: true },
                    inputCharacter: { display: false },
                    fixCharacter: { display: false },
                    seriaStartNo: { display: false },
                    seriaStep: { display: false },
                    cycleFlag: { display: false },
                    cycleMethod: { display: false },
                  }
                } else if (val === 'INPUTCHAR') {
                  return {
                    dateFormat: { display: false },
                    inputCharacter: { display: true },
                    fixCharacter: { display: false },
                    seriaStartNo: { display: false },
                    seriaStep: { display: false },
                    cycleFlag: { display: false },
                    cycleMethod: { display: false },
                  }
                } else if (val === 'FIXCHAR') {
                  return {
                    dateFormat: { display: false },
                    inputCharacter: { display: false },
                    fixCharacter: { display: true },
                    seriaStartNo: { display: false },
                    seriaStep: { display: false },
                    cycleFlag: { display: false },
                    cycleMethod: { display: false },
                  }
                } else if (val === 'SERIALNO') {
                  return {
                    dateFormat: { display: false },
                    inputCharacter: { display: false },
                    fixCharacter: { display: false },
                    seriaStartNo: { display: true },
                    seriaStep: { display: true },
                    cycleFlag: { display: true },
                    cycleMethod: { display: false },
                  }
                } else {
                  return {
                    dateFormat: { display: false },
                    inputCharacter: { display: false },
                    fixCharacter: { display: false },
                    seriaStartNo: { display: false },
                    seriaStep: { display: false },
                    cycleFlag: { display: false },
                    cycleMethod: { display: false },
                  }
                }
              },
            },
            {
              label: '日期时间格式',
              prop: 'dateFormat',
              hide: true
            },
            {
              label: '输入字符',
              prop: 'inputCharacter',
              hide: true
            },
            {
              label: '固定字符',
              prop: 'fixCharacter',
              hide: true
            },
            {
              label: '起始流水号',
              prop: 'seriaStartNo',
              type: 'number',
              hide: true
            },
            {
              label: '流水号步长',
              prop: 'seriaStep',
              type: 'number',
              hide: true
            }, {
              label: '是否循环',
              prop: 'cycleFlag',
              type: 'radio',
              dicData: [
                {
                  label: '是',
                  value: 'Y',
                },
                {
                  label: '否',
                  value: 'N',
                },
              ],
              control: (val, form) => {
                if (val === 'Y') {
                  return {
                    cycleMethod: {
                      display: true
                    }
                  }
                } else {
                  return {
                    cycleMethod: {
                      display: false
                    }
                  }
                }
              },
              hide: true
            }, {
              label: '循环方式',
              prop: 'cycleMethod',
              type: 'select',
              dicUrl: '/blade-system/dict/dictionary?code=sys_autocode_cyclemethod',
              props: {
                label: 'dictValue',
                value: 'dictKey',
              },
              hide: true
            },
            {
              label: '备注',
              prop: 'remark',
              span: 24,
            },
          ],
        },
      };
    },
    computed: {
      ...mapGetters(['userInfo', 'permission']),
      permissionList() {
        return {
          addBtn: this.validData(this.permission.system_autocode_index_add),
          viewBtn: this.validData(this.permission.system_autocode_index_view),
          delBtn: this.validData(this.permission.system_autocode_index_delete),
          editBtn: this.validData(this.permission.system_autocode_index_update)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(',');
      },
    },
    mounted() {
      this.initData();
    },
    methods: {
      initData() {
      },
      handleAdd(row) {
        this.formChild.dictValue = '';
        this.formChild.dictKey = '';
        this.formChild.sort = 0;
        this.formChild.isSealed = 0;
        this.formChild.remark = '';
        this.formChild.ruleId = row.id;
        this.$refs.crudChild.rowAdd();
      },
      rowSave(row, done, loading) {
        const form = {
          ...row,
        };
        add(form).then(
          () => {
            this.onLoadParent(this.pageParent);
            this.$message({
              type: 'success',
              message: '操作成功!',
            });
            done();
          },
          error => {
            window.console.log(error);
            loading();
          }
        );
      },
      rowUpdate(row, index, done, loading) {
        update(row).then(
          () => {
            this.onLoadParent(this.pageParent);
            this.$message({
              type: 'success',
              message: '操作成功!',
            });
            this.onLoadChild(this.pageChild);
            done();
          },
          error => {
            window.console.log(error);
            loading();
          }
        );
      },
      rowDel(row) {
        this.$confirm('确定将选择数据删除?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            return remove(row.id);
          })
          .then(() => {
            this.onLoadParent(this.pageParent);
            this.$message({
              type: 'success',
              message: '操作成功!',
            });
          });
      },
      handleRowClick(row) {
        this.query = {};
        this.ruleId = row.id;
        this.dictValue = row.ruleName;
        this.formChild.ruleId = row.id;
        this.box = true;
        this.onLoadChild(this.pageChild);
      },
      searchReset() {
        this.query = {};
        this.onLoadParent(this.pageParent);
      },
      searchChange(params, done) {
        this.query = params;
        this.pageParent.currentPage = 1;
        this.onLoadParent(this.pageParent, params);
        done();
      },
      selectionChange(list) {
        this.selectionList = list;
      },
      selectionClear() {
        this.selectionList = [];
        this.$refs.crud.toggleSelection();
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning('请选择至少一条数据');
          return;
        }
        this.$confirm('确定将选择数据删除?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            return remove(this.ids);
          })
          .then(() => {
            this.onLoadParent(this.pageParent);
            this.$message({
              type: 'success',
              message: '操作成功!',
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (['edit', 'view'].includes(type)) {
          getRule(this.formParent.id).then(res => {
            this.formParent = res.data.data;
          });
        }
        done();
      },
      currentChange(currentPage) {
        this.pageParent.currentPage = currentPage;
      },
      sizeChange(pageSize) {
        this.pageParent.pageSize = pageSize;
      },
      refreshChange() {
        this.onLoadParent(this.pageParent, this.query);
      },
      rowSaveChild(row, done, loading) {
        row.ruleId = this.ruleId;
        addPart(row).then(
          () => {
            this.onLoadChild(this.pageChild);
            this.$message({
              type: 'success',
              message: '操作成功!',
            });
            done();
          },
          error => {
            window.console.log(error);
            loading();
          }
        );
      },
      rowUpdateChild(row, index, done, loading) {
        row.ruleId = this.ruleId;
        updatePart(row).then(
          () => {
            this.onLoadChild(this.pageChild);
            this.$message({
              type: 'success',
              message: '操作成功!',
            });
            done();
          },
          error => {
            window.console.log(error);
            loading();
          }
        );
      },
      rowDelChild(row) {
        this.$confirm('确定将选择数据删除?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            return removePart(row.id);
          })
          .then(() => {
            this.onLoadChild(this.pageChild);
            this.$message({
              type: 'success',
              message: '操作成功!',
            });
          });
      },
      searchResetChild() {
        this.query = {};
        this.onLoadChild(this.pageChild);
      },
      searchChangeChild(params, done) {
        this.query = params;
        this.pageChild.currentPage = 1;
        this.onLoadChild(this.pageChild, params);
        done();
      },
      selectionChangeChild(list) {
        this.selectionList = list;
      },
      selectionClearChild() {
        this.selectionList = [];
        this.$refs.crudChild.toggleSelection();
      },
      handleDeleteChild() {
        if (this.selectionList.length === 0) {
          this.$message.warning('请选择至少一条数据');
          return;
        }
        this.$confirm('确定将选择数据删除?', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        })
          .then(() => {
            return removePart(this.ids);
          })
          .then(() => {
            this.onLoadChild(this.pageChild);
            this.$message({
              type: 'success',
              message: '操作成功!',
            });
            this.$refs.crudChild.toggleSelection();
          });
      },
      beforeOpenChild(done, type) {
        if (['add', 'edit'].includes(type)) {
          this.initData();
        }
        if (['edit', 'view'].includes(type)) {
          getPart(this.formChild.id).then(res => {
            this.formChild = res.data.data;
          });
        }
        done();
      },
      beforeCloseChild(done) {
        this.$refs.crudChild.modelValue.ruleId = this.ruleId;
        done();
      },
      currentChangeChild(currentPage) {
        this.pageChild.currentPage = currentPage;
      },
      sizeChangeChild(pageSize) {
        this.pageChild.pageSize = pageSize;
      },
      refreshChangeChild() {
        this.onLoadChild(this.pageChild, this.query);
      },
      onLoadParent(page, params = {}) {
        this.loading = true;
        getParentList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(
          res => {
            const data = res.data;
            this.pageParent.total = data.total;
            this.dataParent = data.records;
            this.loading = false;
            this.selectionClear();
          }
        );
      },
      onLoadChild(page, params = {}) {
        this.loadingChild = true;
        getChildList(
          page.currentPage,
          page.pageSize,
          this.ruleId,
          Object.assign(params, this.query)
        ).then(res => {
          const data = res.data;
          this.dataChild = data.records;
          this.loadingChild = false;
          this.selectionClear();
        });
      },
    },
  };
</script>