<template>
  <el-row class="page-container dict">
    <el-container class="page-main" :gutter="20">
      <el-aside width="250px" class="left-content">
        <el-col :span="24" class="left-search">
          <el-input
            v-model.trim="searchVal"
            clearable
            :placeholder="placeholder"
          >
          </el-input>
        </el-col>
        <el-col class="dict-list" ref="dict">
          <el-col
            v-for="(item, index) in tableList"
            :key="item.id"
            class="dict-item"
          >
            <span
              @click="handClick(index, item)"
              :class="{ active: index == isActive }"
              style="cursor: pointer"
            >
              <strong>
                {{ item.label }}
              </strong>
              - {{ item.value }}
            </span>
          </el-col>
        </el-col>
      </el-aside>
      <el-main>
        <el-button type="primary" @click="handleClone">引用配置</el-button>
        <div style="text-align: right">
          <el-input
            v-model.trim="keyWord"
            clearable
            placeholder="关键字"
            style="width: 220px; margin-right: 5px"
          >
          </el-input>
          <el-button
            type="primary"
            v-if="tableCode === 'data_lab_detail'"
            @click="handleAdd"
            >新增(检验细项)</el-button
          >
        </div>
        <el-table-self
          style="margin-top: 10px"
          ref="table"
          :table-data="
            tableCode === 'data_lab_detail' ? configuredFields : fields
          "
          :columns="columns"
          :list-loading="listLoading"
        />
      </el-main>
      <dialog-form
        width="650px"
        :close-modal="false"
        label-width="140px"
        ref="dialog"
        title="引用其他机构协作组配置"
        :form-data="formData"
        @handleConfirm="handleConfirm"
      ></dialog-form>
      <el-drawer
        title="配置字段"
        :visible.sync="widgetVisible"
        :size="500"
        :wrapperClosable="false"
      >
        <div class="drawer__container">
          <div class="drawer__content">
            <div class="widget-config">
              <el-form
                label-suffix="："
                labelPosition="left"
                labelWidth="110px"
                ref="form"
                :rules="rules"
                size="small"
                :model="configForm"
              >
                <el-form-item label="数据模块" prop="firstType">
                  <el-select
                    v-model="configForm.firstType"
                    placeholder="选择数据模块"
                    style="width: 100%"
                    @change="firstTypeChange"
                    clearable
                    filterable
                  >
                    <el-option
                      :label="item.label"
                      :value="item.value"
                      v-for="item in dictMap['data_module']"
                      :key="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="数据子模块">
                  <el-select
                    v-model="configForm.subType"
                    placeholder="选择数据子模块"
                    style="width: 100%"
                    clearable
                    filterable
                  >
                    <el-option
                      :label="item.label"
                      :value="item.value"
                      v-for="item in subTypeOpts"
                      :key="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <div style="margin-bottom: 10px; font-size: 18px">父级字段</div>
                <el-form-item label="父级数据表">
                  <el-select
                    v-model="configForm.parentTableCode"
                    placeholder="选择父级数据表"
                    style="width: 100%"
                    @change="tableChange"
                    clearable
                    filterable
                  >
                    <el-option
                      :label="item.label"
                      :value="item.value"
                      v-for="item in dictMap['table']"
                      :key="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="父级字段">
                  <el-select
                    v-model="configForm.parentFieldCode"
                    placeholder="选择父级字段"
                    style="width: 100%"
                    clearable
                    filterable
                  >
                    <el-option
                      :label="item.label"
                      :value="item.value"
                      v-for="item in parentFieldOpts"
                      :key="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <div style="margin-bottom: 10px; font-size: 18px">
                  当前配置字段
                </div>
                <el-form-item label="字段名称">
                  <el-input
                    v-model="configForm.fieldName"
                    :disabled="isDisabled"
                  ></el-input>
                </el-form-item>
                <el-form-item label="字段编码">
                  <el-input
                    v-model="configForm.fieldCode"
                    :disabled="isDisabled"
                  ></el-input>
                </el-form-item>
                <div style="margin-bottom: 10px; font-size: 18px">完整性</div>

                <el-form-item label="是否必填" labelWidth="130px">
                  <el-switch
                    v-model="configForm.isRequired"
                    :active-value="1"
                    :inactive-value="0"
                  ></el-switch>
                </el-form-item>
                <div style="margin-bottom: 10px; font-size: 18px">有效性</div>
                <el-form-item label="字典值域范围">
                  <el-select
                    v-model="configForm.dictType"
                    placeholder="选择字典"
                    style="width: 100%"
                    @change="dicTypeChange"
                    clearable
                    filterable
                  >
                    <el-option
                      :label="item.name"
                      :value="item.type"
                      v-for="item in dictList"
                      :key="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <div
                  class="el-form-item--small el-form--label-top"
                  style="padding-bottom: 14px"
                >
                  <strong class="el-form-item__label" style="padding: 0"
                    >字典数据示例：</strong
                  >
                  <div class="el-form-item__content">
                    <draggable
                      tag="ul"
                      :list="dicData"
                      :group="{ name: 'dic' }"
                      ghost-class="ghost"
                      handle=".drag-item"
                    >
                      <li v-for="(item, index) in dicData" :key="index">
                        <i
                          class="drag-item el-icon-s-operation"
                          style="font-size: 16px; margin: 0 5px; cursor: move"
                        ></i>
                        <el-input
                          style="margin-right: 5px"
                          size="mini"
                          readonly
                          clearable
                          v-model="item.label"
                          placeholder="label"
                        ></el-input>
                        <el-input
                          size="mini"
                          clearable
                          readonly
                          v-model="item.value"
                          placeholder="value"
                        ></el-input>
                      </li>
                    </draggable>
                  </div>
                </div>
                <el-form-item label="正则表达式">
                  <el-input v-model="configForm.regexStr" clearable></el-input>
                </el-form-item>
                <el-form-item label="Hutool校验">
                  <el-select
                    v-model="configForm.htType"
                    placeholder="选择Hutool校验"
                    style="width: 100%"
                    clearable
                    filterable
                  >
                    <el-option
                      :label="item.label"
                      :value="item.value"
                      v-for="item in dictMap['hutool_validator']"
                      :key="item.id"
                    ></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="文本长度">
                  <div style="display: flex">
                    <el-input-number
                      v-model.trim="configForm.minLen"
                      :min="0"
                      clearable
                      controls-position="right"
                      size="mini"
                      placeholder="最小长度"
                    ></el-input-number>
                    <span style="margin: 0 10px"> - </span>
                    <el-input-number
                      v-model.trim="configForm.maxLen"
                      clearable
                      :min="configForm.minLen + 1"
                      controls-position="right"
                      size="mini"
                      placeholder="最大长度"
                    ></el-input-number>
                  </div>
                </el-form-item>
                <el-form-item label="数值范围">
                  <div style="display: flex">
                    <el-input-number
                      v-model.trim="configForm.minValue"
                      clearable
                      controls-position="right"
                      size="mini"
                      placeholder="最小值"
                    ></el-input-number>
                    <span style="margin: 0 10px"> - </span>
                    <el-input-number
                      v-model.trim="configForm.maxValue"
                      clearable
                      :min="configForm.minValue + 1"
                      controls-position="right"
                      size="mini"
                      placeholder="最大值"
                    ></el-input-number>
                  </div>
                </el-form-item>

                <div style="margin-bottom: 10px; font-size: 18px">一致性</div>
                <el-form-item label="逻辑质控">
                  <el-input
                    v-model.trim="configForm.logicStr"
                    type="textarea"
                    clearable
                    placeholder="逻辑质控"
                  ></el-input>
                </el-form-item>

                <div style="margin-bottom: 10px; font-size: 18px">准确性</div>
                <el-form-item label="逻辑质控">
                  <el-input
                    v-model.trim="configForm.note"
                    type="textarea"
                    clearable
                    placeholder="逻辑质控"
                  ></el-input>
                </el-form-item>
              </el-form>
            </div>
          </div>

          <div class="footer">
            <el-button @click="widgetVisible = false" size="large"
              >取 消</el-button
            >
            <el-button
              size="large"
              type="primary"
              :loading="loading"
              @click="handleConfigConfirm"
              >确 定</el-button
            >
          </div>
        </div>
      </el-drawer>
    </el-container>
  </el-row>
</template>
<script>
import {
  setQcConfigFields,
  getTableFields,
  getQcConfigFields,
  setQcConfigField,
  getQcGroupOption,
  setCloneConf,
  delConf,
} from "@/api/coop-group"
import Draggable from "vuedraggable"
import { mapGetters } from "vuex"
export default {
  name: "QualityControlConfig",
  components: { Draggable },
  props: {
    groupId: String,
    groupName: String,
  },
  data() {
    return {
      isDisabled: true,
      subTypeOpts: [],
      parentFieldOpts: [],
      widgetVisible: false,
      configForm: {
        firstType: "",
        subType: "",
      },
      rules: {
        firstType: [
          { required: true, message: "请选择数据模块", trigger: "change" },
        ],
      },
      isActive: -1,
      placeholder: "搜索数据库",
      name: "",
      searchVal: "",
      keyWord: "",
      typeId: "",
      fieldList: [],
      configuredFieldList: [],
      tableCode: "",
      loading: false,
      listLoading: false,
      configIndex: 0,
      formData: [
        {
          type: "select",
          label: "引用机构/协作组",
          placeholder: "请选择机构/协作组",
          prop: "id",
          opts: [],
          rules: [{ required: true, message: "请选择机构/协作组" }],
        },
      ],
      columns: [
        {
          label: "数据模块",
          minWidth: 120,
          value: "firstType",
          hidden: true,
        },
        {
          label: "数据子模块",
          minWidth: 120,
          value: "subType",
          hidden: true,
        },
        {
          label: "字段名称",
          minWidth: 120,
          value: "fieldName",
        },
        {
          label: "字段code",
          minWidth: 120,
          value: "fieldCode",
        },
        {
          label: "规则",
          minWidth: 200,
          value: "logicStr",
        },

        {
          label: "操作",
          width: 160,
          fixed: "right",
          operType: "button",
          operations: [
            {
              func: this.handleConfig,
              formatter(row) {
                return {
                  label: "配置",
                  type: "text",
                }
              },
            },
            {
              func: this.handleDel,
              style: {
                color: "#F56C6C",
              },
              formatter(row) {
                return {
                  label: "删除配置",
                  type: "text",
                }
              },
            },
          ],
        },
      ],
      dicData: [],
    }
  },

  watch: {
    groupId(groupId) {
      if (groupId) {
        this.getTableFields()
        this.getFields()
      }
    },
    tableCode(tableCode) {
      this.columns[0].hidden = this.columns[1].hidden =
        tableCode === "data_lab_detail" ? false : true
    },
  },

  computed: {
    ...mapGetters({
      dictList: ["dict/dictSet"],
      dictMap: ["dict/dictMap"],
    }),

    // 数据库表过滤
    tableList() {
      const dictTable =
        (this.dictMap["table"] &&
          this.dictMap["table"].filter((_) => _.value !== "data_lab_type")) ||
        []
      const list = dictTable.filter(
        (_) =>
          !this.searchVal ||
          _.label.includes(this.searchVal) ||
          _.value.includes(this.searchVal)
      )
      this.isActive = this.getListIdx(list, this.typeId)
      return list
    },

    fields() {
      return this.fieldList.filter(
        (_) =>
          !this.keyWord ||
          _.fieldName.includes(this.keyWord) ||
          _.fieldCode.includes(this.keyWord)
      )
    },
    configuredFields() {
      return this.configuredFieldList.filter(
        (_) =>
          !this.keyWord ||
          _.fieldName.includes(this.keyWord) ||
          _.fieldCode.includes(this.keyWord)
      )
    },
  },
  methods: {
    handleDel(row) {
      this.$confirm(`是否删除【${row.fieldName || ""}】配置?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delConf(row.id).then((res) => {
            if (res.code === 1) {
              this.$message({
                type: "success",
                message: "删除成功!",
              })
              this.getTableFields()
            }
          })
        })
        .catch(() => {})
    },
    handleClone() {
      if (!this.groupId) {
        this.$message.warning("请先选择协作组")
        return
      }
      this.$refs.dialog.open()
    },
    handleConfirm({ id }) {
      const { diseaseCode, groupId, orgId } = this.formData[0].opts.find(
        (item) => item.groupId === id
      )
      const params = {
        sourceDiseaseCode: diseaseCode,
        sourceGroupId: groupId,
        sourceOrgId: orgId,
        targetGroupId: this.groupId,
      }
      setCloneConf(params).then((res) => {
        this.$message.success("配置成功")
        this.getFields()
        this.$refs.dialog.close()
      })
    },
    handleConfigConfirm() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          const data = Object.assign(
            {
              tableCode: this.tableCode,
              tableName: this.name,
              groupId: this.groupId,
              groupName: this.groupName,
            },
            this.configForm
          )
          this.loading = true
          setQcConfigField(data)
            .then((res) => {
              this.$message.success("配置成功")
              this.getFields()
              this.widgetVisible = false
            })
            .finally(() => {
              this.loading = false
            })
        } else {
        }
      })
    },
    tableChange(tableCode) {
      if (!tableCode) {
        this.parentFieldOpts = []
        return
      }
      getTableFields({ tableCode, groupId: this.groupId }).then((res) => {
        this.parentFieldOpts = res.data.map((_) => {
          return {
            ..._,
            label: _.fieldName,
            value: _.fieldCode,
          }
        })
      })
    },
    firstTypeChange(val, notEmpty = false) {
      let list = []
      const current = this.dictMap["data_module"].find((_) => _.value === val)
      if (current && current.children) {
        list = current.children
      }
      if (!notEmpty) {
        this.$set(this.configForm, "subType", "")
      }
      this.subTypeOpts = list
    },
    dicTypeChange(type) {
      this.dicData = this.deepClone(this.dictMap[type])
    },
    handleAdd() {
      this.handleConfig({}, -1)
    },
    handleConfig(row, index) {
      this.configForm = Object.assign({}, row, {
        maxLen: this.formatter(row.maxLen),
        minLen: this.formatter(row.minLen),
        maxValue: this.formatter(row.maxValue),
        minValue: this.formatter(row.minValue),
      })
      this.dicTypeChange(row.dictType)
      this.firstTypeChange(row.firstType, true)
      this.isDisabled = index > -1
      this.configIndex = index
      this.widgetVisible = true
    },
    formatter(val) {
      return val === "" || val === null ? undefined : val
    },
    getQcGroupOption() {
      getQcGroupOption().then((res) => {
        this.formData[0].opts = res.data.map((item) => {
          return {
            ...item,
            value: item.groupId,
            label: `机构：${item.orgName} | 疾病： ${item.diseaseName} | 协作组： ${item.groupName}`,
          }
        })
      })
    },
    // 点击左侧列表
    handClick(index, { type, label, id, value }) {
      if (!this.groupId) {
        this.$message.warning("请先选择协作组")
        return
      }
      this.name = label
      this.tableCode = value
      this.isActive = index
      this.typeId = id
      this.fieldList = []
      this.getTableFields()
    },
    // 全部字段
    getTableFields() {
      getTableFields({ tableCode: this.tableCode, groupId: this.groupId }).then(
        (res) => {
          this.fieldList = res.data
          this.getFields()
        }
      )
    },
    // 已配置字段
    getFields() {
      if (!this.tableCode) return
      getQcConfigFields({ tableCode: this.tableCode, groupId: this.groupId })
        .then((res) => {
          this.configuredFieldList = res.data
          this.fieldList = this.fieldList.map((field) => {
            let configuredField = this.configuredFieldList.find(
              (_) => _.fieldCode === field.fieldCode
            )
            return {
              ...field,
              ...configuredField,
            }
          })
        })
        .catch((e) => {
          this.configuredFieldList = []
        })
    },
    // 批量保存
    handleSave() {
      if (!this.groupId) {
        this.$message.warning("请先选择协作组")
        return
      }
      const table = {
        tableCode: this.tableCode,
        tableName: this.name,
        groupId: this.groupId,
        groupName: this.groupName,
      }
      const fieldList =
        this.tableCode === "data_lab_detail"
          ? this.configuredFieldList
          : this.fieldList
      const list = fieldList
        .filter((_) => _.firstType)
        .map((_) => {
          return {
            ..._,
            ...table,
          }
        })
      if (!list.length) {
        this.$message.warning("没有可保存的数据")
        return
      }
      this.loading = true
      setQcConfigFields(table, list)
        .then((res) => {
          this.$message.success("配置成功")
          this.getFields()
        })
        .finally(() => {
          this.loading = false
        })
    },

    getListIdx(list = [], id) {
      let listIdx = -1
      for (var i = 0; i < list.length; i++) {
        if (list[i].id === id) {
          listIdx = i
          break
        }
      }
      return listIdx
    },
  },
  created() {
    this.getQcGroupOption()
  },
}
</script>
<style lang="scss" scoped>
::v-deep .el-main {
  padding: 0px 0 0 10px;
}

.drawer__container {
  padding: 0 20px;
  .drawer__content {
    height: calc(100vh - #{"160px"});
    overflow-y: auto;

    ::v-deep .el-input-number {
      width: 100%;
    }
    &::-webkit-scrollbar {
      width: 0px;
      height: 0px;
    }
    &::-webkit-scrollbar-thumb {
      background-color: #fff;
    }
  }
  .footer {
    margin-top: 20px;
    display: flex;
    button {
      flex: 1;
    }
  }
}
</style>
