<template>
  <div class="fields-config">
    <el-drawer
      :title="title"
      v-model="dialogVisible"
      direction="rtl"
      size="100%"
      :close-on-click-modal="false"
      :before-close="handleClose"
    >
      <el-form
        v-loading="loading"
        element-loading-text="字段太多啦，疯狂加载中..."
        ref="form"
        class="body-box"
        :model="form"
      >
        <el-table :data="form.tableData">
          <el-table-column label="操作" width="55" fixed>
            <template v-slot="{ row, $index }">
              <el-popover placement="top" :width="180" :ref="`pop${$index}`">
                <div>
                  <div
                    class="cursor-pointer px-10px py-6px hover:bg-slate-100"
                    @click="handleClickInsertRow($index, 1)"
                    >在上方插入一级表头
                  </div>
                  <div
                    class="cursor-pointer px-10px py-6px hover:bg-slate-100"
                    @click="handleClickInsertRow($index, 2)"
                    >在上方插入二级表头
                  </div>
                  <!-- 只能删除表单头 行 -->
                  <div
                    class="cursor-pointer px-10px py-6px hover:bg-slate-100"
                    v-show="row.inputType === 16 || row.inputType === 17"
                    @click="handleClickInsertRow($index, 3)"
                    >删除当前表头
                  </div>
                </div>
                <template #reference>
                  <el-icon>
                    <MoreFilled />
                  </el-icon>
                </template>
              </el-popover>
            </template>
          </el-table-column>
          <!-- <el-table-column label="序号" width="55" fixed>
            <template v-slot="{ $index }">
              <el-form-item>
                <div>
                  {{ $index + 1 }}
                </div>
              </el-form-item>
            </template>
          </el-table-column> -->
          <el-table-column prop="fieldName" label="字段名称" min-width="110" fixed>
            <template v-slot="{ row, $index }">
              <el-form-item :prop="`tableData[${$index}].fieldName`">
                <div>{{ row.fieldName }}</div>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="fieldDesc" label="字段说明" min-width="110" fixed>
            <template v-slot="{ row, $index }">
              <el-form-item :prop="`tableData[${$index}].fieldDesc`">
                <div>{{ row.fieldDesc }}</div>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="orderNo" label="排序号" width="80">
            <template v-slot="{ row, $index }">
              <el-form-item :prop="`tableData[${$index}].orderNo`">
                <el-input
                  v-model.number="row.orderNo"
                  @input="
                    (val) => {
                      row.orderNo = val.replace(/[^\d]/g, '')
                    }
                  "
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="inputType" label="输入类型" width="170">
            <template v-slot="{ row, $index }">
              <el-form-item :prop="`tableData[${$index}].inputType`">
                <el-select
                  v-model="row.inputType"
                  clearable
                  @change="selectInputType(row.inputType, $index)"
                >
                  <el-option
                    v-for="item in getCodeByType('INPUT_TYPE')"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="formHead" label="输入说明" width="170">
            <template v-slot="{ row, $index }">
              <el-form-item :prop="`tableData[${$index}].formHead`">
                <el-input v-model="row.formHead" placeholder="请输入" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column
            prop="deptAuth"
            label="部门权限"
            width="200"
            v-if="currentRow.pageTemplate !== 'custom'"
          >
            <template v-slot="{ row, $index }">
              <el-form-item :prop="`tableData[${$index}].deptAuth`">
                <el-cascader
                  v-model="row.deptAuth"
                  :props="deptTreeProps"
                  :options="deptTreeData"
                  clearable
                  collapse-tags
                  collapse-tags-tooltip
                  :showAllLevels="false"
                  @change="(val) => handleChangeDept(val, row, $index)"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="contactType" label="关联数据类型" width="140">
            <template v-slot="{ row, $index }">
              <el-form-item :prop="`tableData[${$index}].contactType`">
                <el-select
                  v-if="isShowSelect(row.inputType)"
                  v-model="row.contactType"
                  clearable
                  @change="selectAboutType(row.contactType, $index)"
                >
                  <el-option
                    v-for="item in aboutDataOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
                <div v-else>
                  {{ (row.contactType = '') }}
                </div>
              </el-form-item>
            </template>
          </el-table-column> -->
          <el-table-column prop="contactNo" align="center" label="关联数据" width="200">
            <template v-slot="{ row, $index }">
              <el-form-item :prop="`tableData[${$index}].contactNo`">
                <el-select v-model="row.contactNo" clearable filterable>
                  <!-- 18 子表单 时 单独处理 -->
                  <el-option
                    v-for="item in row.inputType === '18'
                      ? getCodeByType('TEMPLATE_CODE')
                      : dictionaryOptions"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="defaultValue" label="默认值" width="100">
            <template v-slot="{ row, $index }">
              <el-form-item :prop="`tableData[${$index}].defaultValue`">
                <el-input v-model="row.defaultValue" placeholder="请输入" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="isAddReadonly" align="center" label="是否只读" width="80">
            <template v-slot="{ row, $index }">
              <el-form-item :prop="`tableData[${$index}].isAddReadonly`">
                <el-switch v-model="row.isAddReadonly" active-value="1" inactive-value="0" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="isFormShow" align="center" label="是否在表单显示" width="80">
            <template v-slot="{ row, $index }">
              <el-form-item :prop="`tableData[${$index}].isFormShow`">
                <el-switch v-model="row.isFormShow" active-value="1" inactive-value="0" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="isNull" align="center" label="是否必选" width="80">
            <template v-slot="{ row, $index }">
              <el-form-item :prop="`tableData[${$index}].isNull`">
                <el-switch v-model="row.isNull" active-value="1" inactive-value="0" />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="limitLength" label="限制长度">
            <template v-slot="{ row, $index }">
              <el-form-item :prop="`tableData[${$index}].limitLength`">
                <el-input
                  v-model.number="row.limitLength"
                  :maxlength="4"
                  @input="
                    (val) => {
                      row.limitLength = val.replace(/[^\d]/g, '')
                    }
                  "
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="valueType" label="限制类型" width="170">
            <template v-slot="{ row, $index }">
              <el-form-item :prop="`tableData[${$index}].valueType`">
                <el-select v-model="row.valueType" clearable>
                  <el-option
                    v-for="item in getCodeByType('VALUE_TYPE')"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  />
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="isListShow" align="center" label="是否在列表显示">
            <template v-slot="{ row, $index }">
              <el-form-item :prop="`tableData[${$index}].isListShow`">
                <el-switch v-model="row.isListShow" active-value="1" inactive-value="0" />
              </el-form-item>
            </template>
          </el-table-column>
          <!-- <el-table-column prop="listWidth" label="展示列宽">
            <template v-slot="{ row, $index }">
              <el-form-item :prop="`tableData[${$index}].listWidth`">
                <el-input
                  v-model.number="row.listWidth"
                  :maxlength="10"
                  @input="
                    (val) => {
                      row.listWidth = val.replace(/[^\d]/g, '')
                    }
                  "
                />
              </el-form-item>
            </template>
          </el-table-column> -->
          <el-table-column prop="isSearch" align="center" label="是否查询">
            <template v-slot="{ row, $index }">
              <el-form-item :prop="`tableData[${$index}].isSearch`">
                <el-switch v-model="row.isSearch" active-value="1" inactive-value="0" />
              </el-form-item>
            </template>
          </el-table-column>
        </el-table>
      </el-form>
      <div class="footer-btns">
        <el-button type="primary" @click="submit"> 保存</el-button>
        <el-button @click="handleClose"> 取消</el-button>
      </div>
    </el-drawer>
  </div>
</template>
<script>
import {
  findFieldConfigById,
  queryTypeList,
  updateFieldConfig
} from '@common/src/api/system-config/field'
import { getCodeByType } from '@common/src/utils'
import { getDeptTree } from '@common/src/api/system-config/department'

import {
  ElDrawer,
  ElForm,
  ElFormItem,
  ElTable,
  ElTableColumn,
  ElInput,
  ElSelect,
  ElOption,
  ElButton,
  ElCheckbox,
  ElSwitch,
  ElMessage,
  ElPopover,
  ElIcon,
  ElCascader
} from 'element-plus'

export default {
  name: 'FieldsConfigDialog',
  components: {
    ElDrawer,
    ElForm,
    ElFormItem,
    ElTable,
    ElTableColumn,
    ElInput,
    ElSelect,
    ElOption,
    ElButton,
    // ElCheckbox,
    ElSwitch,
    // eslint-disable-next-line vue/no-unused-components
    ElMessage,
    ElPopover,
    ElIcon,
    ElCascader
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    currentRow: {
      type: Object,
      defalt: () => {}
    }
  },
  data() {
    return {
      getCodeByType,
      title: '字段配置',
      dialogVisible: false,
      // 关联数据类型的下拉列表
      aboutDataOptions: [
        {
          value: '1',
          label: '业务字典表'
        }
        // {
        //   value: 2,
        //   label: '业务数据表'
        // },
      ],
      form: this.getDefaultForm(),
      currentAboutData: {},
      dictionaryOptions: [], // 存放业务表
      buesinessTableList: [], // 存放业务数据表
      maxHeight: 0,
      deptTreeData: [],
      deptTreeProps: {
        value: 'id',
        label: 'name',
        multiple: true,
        emitPath: false,
        checkStrictly: true
      },
      loading: false
    }
  },
  computed: {
    id() {
      return this.currentRow?.id
    }
  },
  watch: {
    visible(visible) {
      this.dialogVisible = visible
      if (visible) {
        this.loadData()
      }
    },
    dialogVisible(visible) {
      this.$emit('update:visible', visible)
    }
  },
  methods: {
    loadData() {
      this.loading = true
      this.queryTypeList()
      // this.getDataTableListAll()
      this.findFieldConfigById()
    },

    // 查询字段配置的详情
    async findFieldConfigById() {
      const { data, success } = await findFieldConfigById(this.id)
      if (success) {
        this.form.tableData = data.map((item) => {
          item.deptAuth = (item.deptAuth && item.deptAuth.split(',').map((i) => Number(i))) || null
          return item
        })

        this.loading = false

        this.getDeptTree()
      }
    },
    // 部门
    async getDeptTree() {
      const { success, data } = await getDeptTree()
      if (success) {
        this.deptTreeData = data
      }
    },
    // 获取业务数据表下拉列表- 1. 传给数据表弹窗使用
    async getDataTableListAll() {
      const { data, success } = await getDataTableListAll()
      if (success) this.buesinessTableList = data // key:id, value: tableName
    },
    // 获取业务字典下拉列表- 1，传给业务字典弹窗使用，2，匹配关联数据根据value显示name
    async queryTypeList() {
      const { data, success } = await queryTypeList()
      if (success)
        this.dictionaryOptions = data.map((i) => {
          return {
            label: i.typeName,
            value: i.codeType
          }
        })
      // key: codeType, value: typeName
    },
    getDefaultForm() {
      return {
        tableData: [
          {
            fieldName: '',
            fieldDesc: '',
            orderNo: 0,
            inputType: '',
            contactType: '',
            contactNo: '',
            defaultValue: '',
            isNull: '', // 是否必填 0-否，1-是
            limitLength: 0,
            isListShow: '', // 是否列表中展示(0:否，1:是)
            listWidth: 0,
            isSearch: '', // 0-否，1-是
            isAddReadonly: '', // 0-否，1-是
            isFormShow: '' // 是否在表单显示 0-否，1-是
          }
        ]
      }
    },
    handleClose() {
      this.dialogVisible = false
      this.form = this.getDefaultForm()
    },
    // 处理数据，进行保存
    dealData(list) {
      const arr = list.map((item) => {
        item.type = item.id ? 2 : 1
        // 部门
        item.deptAuth = (item.deptAuth && item.deptAuth.join(',')) || null
        return item
      })
      return {
        serviceTableId: this.id,
        updateServiceTableFieldBoList: arr
      }
    },
    submit() {
      const params = this.dealData(this.form.tableData)
      updateFieldConfig(params).then((success, message) => {
        if (success) {
          this.$emit('save')
          this.handleClose()
          // ElMessage({
          //   type: 'success',
          //   message: '操作成功'
          // })
        }
      })
    },
    // 输入类型 选择框切换时触发
    selectInputType(val, index) {
      // 当输入类型选中的不为【下拉列表】时，关联数据类型和关联数据以及点开关联数据弹窗里的数据 置空
      if (!this.isShowSelect(val)) {
        this.form.tableData[index].contactNo = ''
        this.form.tableData[index].contactType = ''
      }
    },
    // 关联数据类型下拉列表选中触发
    selectAboutType(val, index) {
      if (!val) {
        this.form.tableData[index].contactType = ''
      }
      // 当关联数据类型切换时，将关联数据置空重置
      this.form.tableData[index].contactNo = ''
    },
    // 判断关联数据类型是否展示下拉选择框
    isShowSelect(type) {
      const toSelectList = [3, 4, 5, 6, 11, 13, 14, 15] // 当输入类型是该数组中的值时，说明关联数据类型需要展示下拉选择框
      return toSelectList.indexOf(Number(type)) > -1
    },
    /**
     * @description: 手动插入表单头
     * @param {*} index 当前行索引
     * @param {*} type 是一级还是二级 1 2 3：删除
     * @return {*}
     */
    handleClickInsertRow(index, type) {
      if (type === 3) {
        this.form.tableData.splice(index, 1)
      } else {
        const fromHeadRow = {
          fieldDesc: type === 1 ? '一级表单头' : '二级表单头',
          inputType: type === 1 ? '16' : '17'
        }
        this.form.tableData.splice(index, 0, fromHeadRow)
      }

      // 关闭pop
      this.$refs[`pop${index}`].hide()
    },
    // 默认在一级表头上 设置部门权限 然后将该表头下面所属的表单 都默认设置上
    handleChangeDept(val, row, index) {
      if (row.inputType === '16') {
        const data = this.form.tableData
        for (let i = index + 1; i < data.length; i++) {
          if (data[i].inputType !== '16') {
            data[i].deptAuth = val
          } else return
        }
      }
    }
  }
}
</script>
<style lang="less" scoped>
:deep(.el-drawer__body) {
  height: calc(100% - 57px);
  padding: 0;

  .el-select {
    width: 100%;
  }
}

:deep(.el-drawer__header) {
  color: #333;
  font-weight: 500;
  font-size: 16px;
  padding: 14px 24px;
  border-bottom: 1px solid #e6e6e6;
  margin-bottom: 0;
}

.body-box {
  height: calc(100% - 65px);
  padding: 24px;
  overflow: auto;
}

.footer-btns {
  height: 64px;
  line-height: 64px;
  // box-shadow: 2px 2px 12px 0px rgba(0, 0, 0, 0.6);
  text-align: right;
  padding-right: 44px;
  border-top: 1px solid #e6e6e6;
}

:deep(.el-form-item.el-form-item) {
  margin-bottom: 0;
}
</style>
