<template>
  <div class="container">
    <direct-search
      ref="form"
      :label-position="'right'"
      :forms="searchList"
      :style="{ textAlign: 'left' }"
      @handleSearch="handleFormSearch"
    />
    <el-table-self
      ref="table"
      :table-data="tableData"
      :columns="columns"
      :list-loading="listLoading"
      :current-page="pageIndex"
      :total-count="total"
      :page-sizes="pageSizes"
      :page-size="pageSize"
      @pageSizeChange="handleSizeChange"
      @currentPageChange="handleCurrentChange"
    />

    <dialog-form
      width="750px"
      ref="dialog"
      :title="formEdit.id ? '编辑' : '新增'"
      :form-edit="formEdit"
      :form-data="formData"
      labelWidth="120px"
      @handleConfirm="handleConfirm"
    ></dialog-form>

    <dialog-form-self ref="inputAdd"></dialog-form-self>
  </div>
</template>

<script>
import WidgetConfig from "packages/WidgetConfig.vue"
import DialogFormSelf from "./DialogFormSelf"
import paginationMixin from "@/components/TabComponents/mixin"
import {
  getFeignFieldPage,
  feignField,
  delFeignField,
  getFieldListByCode,
  getGroupFormTableList,
} from "@/api/field.js"
import { getCoopGroupList, getGroupFormList } from "@/api/coop-group.js"
export default {
  name: "FieldMapping",
  components: {
    WidgetConfig,
    DialogFormSelf,
  },
  mixins: [paginationMixin],
  data() {
    return {
      listLoading: false,
      // 查询列表
      searchList: [
        {
          label: "原表code",
          type: "input",
          prop: "sourceTableCode",
          placeholder: "请输入原表code",
        },
        {
          label: "原字段code",
          type: "input",
          prop: "sourceFieldCode",
          placeholder: "请输入原字段code",
        },

        {
          label: "目标表code",
          type: "input",
          prop: "targetTableCode",
          placeholder: "请输入目标表code",
        },
        {
          label: "目标字段code",
          type: "input",
          prop: "targetFieldCode",
          placeholder: "请输入目标字段code",
        },
        {
          label: "机构名",
          type: "input",
          prop: "orgName",
          placeholder: "请输入机构名",
        },
        {
          label: "专病名",
          type: "input",
          prop: "diseaseName",
          placeholder: "请输入专病名",
        },
        {
          label: "创建人",
          type: "input",
          prop: "createUser",
          placeholder: "请输入创建人",
        },
        {
          type: "button",
          value: "查询",
          icon: "el-icon-search",
        },
        {
          type: "button",
          color: "primary",
          icon: "el-icon-plus",
          hasForm: true,
          value: "添加",
          func: this.handleAdd,
        },
        {
          type: "button",
          color: "primary",
          icon: "el-icon-plus",
          hasForm: true,
          value: "输入添加",
          func: this.handleInputAdd,
        },
      ],
      columns: [
        {
          label: "协作组名",
          minWidth: 120,
          value: "groupName",
        },
        {
          label: "疾病名",
          minWidth: 120,
          value: "diseaseName",
        },
        {
          label: "表单类型",
          minWidth: 120,
          value: "formType",
          formatter: (row) => {
            return this.$handle.formatDicList(
              this.dictMap["formType"],
              String(row.formType)
            )
          },
        },

        {
          label: "原表code",
          minWidth: 120,
          value: "sourceTableCode",
        },

        {
          label: "原字段code",
          minWidth: 120,
          value: "sourceFieldCode",
        },

        {
          label: "表单名称",
          minWidth: 120,
          value: "formName",
        },

        {
          label: "目标表code",
          minWidth: 120,
          value: "targetTableCode",
        },
        {
          label: "目标字段code",
          minWidth: 120,
          value: "targetFieldCode",
        },
        {
          label: "创建时间",
          minWidth: 180,
          value: "createTime",
        },
        {
          label: "操作",
          width: 220,
          fixed: "right",
          operType: "button",
          operations: [
            {
              func: this.handleCopyAdd,
              formatter(row) {
                return {
                  label: " 复制新增",
                  type: "primary",
                }
              },
            },
            {
              type: "dropdown",
              children: [
                {
                  func: this.handleAdd,
                  icon: "el-icon-edit-outline",
                  label: "编辑",
                  style: {
                    color: "#409EFF",
                  },
                },
                {
                  func: this.handleInputCopyAdd,
                  label: "输入复制新增",
                  icon: "el-icon-document-copy",
                  style: {
                    color: "#409EFF",
                  },
                },
                {
                  func: this.handleInputAdd,
                  label: "输入编辑",
                  icon: "el-icon-edit-outline",
                  style: {
                    color: "#E6A23C",
                  },
                },
                {
                  func: this.handleDel,
                  label: "删除",
                  icon: "el-icon-delete",
                  style: {
                    color: "#F56C6C",
                  },
                },
              ],
            },
          ],
        },
      ],
      formEdit: {},
      formData: [
        {
          label: "疾病名",
          prop: "diseaseName",
          spanCount: 12,
          type: "input",
        },
        {
          label: "机构名",
          prop: "orgName",
          spanCount: 12,
          type: "input",
        },
        {
          label: "协作组",
          prop: "groupId",
          spanCount: 12,
          type: "select",
          func: this.groupChange,
          opts: [],
        },
        {
          label: "表单",
          prop: "formId",
          spanCount: 12,
          type: "select",
          func: this.formChange,
          opts: [],
        },
        {
          label: "原表名",
          prop: "sourceTableName",
          spanCount: 12,
          type: "input",
        },
        {
          label: "原表code",
          prop: "sourceTableCode",
          spanCount: 12,
          type: "input",
        },
        {
          label: "原字段名",
          prop: "sourceFieldName",
          spanCount: 12,
          type: "input",
        },
        {
          label: "原字段code",
          prop: "sourceFieldCode",
          spanCount: 12,
          type: "input",
        },
        {
          label: "目标表名",
          spanCount: 12,
          type: "select",
          prop: "targetTableCode",
          func: this.targetTableNameChange,
          opts: [],
        },
        {
          label: "目标字段名",
          type: "select",
          spanCount: 12,
          func: this.targetFieldCodeChange,
          prop: "targetFieldCode",
          opts: [],
        },
        {
          label: "字典",
          type: "input",
          spanCount: 12,
          prop: "dictType",
        },
        {
          label: "创建人",
          prop: "createUser",
          spanCount: 12,
          type: "input",
        },
        {
          label: "格式化方式",
          prop: "formatType",
          spanCount: 12,
          type: "select",
          optsFormatter: () => {
            return this.dictMap && this.dictMap["data_format_type"]
          },
        },
      ],
      tableData: [],
      cacheForm: {},
    }
  },

  methods: {
    // 获得协作组列表
    getCoopGroupList() {
      getCoopGroupList().then((res) => {
        const d = res.data
        this.formData[2].opts = d.map((item) => {
          return {
            label: item.groupName,
            value: item.id,
          }
        })
      })
    },
    targetFieldCodeChange(val) {
      let dictType = ""
      this.formData[9].opts.some((item) => {
        if (item.value === val) {
          dictType = item.dictType
          return true
        }
      })
      this.$refs.dialog.initFields({ dictType })
    },

    groupChange(groupId) {
      const list = []
      this.$refs.dialog.initFields({ formId: "" })
      if (!groupId) {
        this.formData[3].opts = list
        return
      }
      getGroupFormList({ groupId }).then((res) => {
        const d = res.data
        d.forEach((item) => {
          list.push({
            label: item.formName,
            value: item.formId,
            type: item.type,
          })
        })
        this.formData[3].opts = list
      })
    },

    formChange(formId) {
      const list = []
      this.$refs.dialog.initFields({ targetTableCode: "" })
      if (!formId) {
        this.formData[8].opts = list
        return
      }
      getGroupFormTableList({ formId }).then((res) => {
        const d = res.data
        d.forEach((item) => {
          list.push({
            label: item.tableName,
            value: item.tableCode,
          })
        })
        this.formData[8].opts = list
      })
    },

    targetTableNameChange(tableCode) {
      const list = []
      this.$refs.dialog.initFields({ targetFieldCode: "" })
      if (!tableCode) {
        this.formData[9].opts = list
        return
      }
      getFieldListByCode({ tableCode }).then((res) => {
        const d = res.data
        d.forEach((item) => {
          let jsonObj = item.jsonStr ? JSON.parse(item.jsonStr) : {}
          let dictType = jsonObj.dicType || ""
          list.push({
            label: item.fieldName,
            value: item.fieldCode,
            dictType,
          })
        })
        this.formData[9].opts = list
      })
    },
    handleCopyAdd(row) {
      const data = Object.assign({}, row)
      delete data.id
      this.handleAdd(data)
    },
    handleAdd(row) {
      this.formEdit = Object.assign({}, row)
      const { targetTableCode, groupId, formId, targetFieldCode } = row
      this.groupChange(groupId)
      this.formChange(formId)
      this.targetTableNameChange(targetTableCode)
      this.$refs.dialog.open()
    },

    handleInputCopyAdd(row) {
      const data = Object.assign({}, row)
      delete data.id
      this.$refs.inputAdd.handleAdd(data)
    },
    handleInputAdd(row) {
      this.$refs.inputAdd.handleAdd(row)
    },

    handleConfirm(form) {
      const data = Object.assign({}, form)
      const currentForms =
        this.formData[3].opts.find((_) => _.value === form.formId) || {}
      data.groupName = this.$handle.formatDicList(
        this.formData[2].opts,
        form.groupId
      )
      data.formType = currentForms.type
      data.formName = currentForms.label
      data.targetTableName = this.$handle.formatDicList(
        this.formData[8].opts,
        form.targetTableCode
      )
      data.targetFieldName = this.$handle.formatDicList(
        this.formData[9].opts,
        form.targetFieldCode
      )

      const msg = data.id ? "编辑成功" : "新增成功"
      feignField(data).then((res) => {
        if (res.code === 1) {
          this.$message.success(msg)
          this.$refs.dialog.close()
          this.handleSearch()
        }
      })
    },
    handleDel(row) {
      this.$confirm(`是否删除?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          delFeignField(row.id).then((res) => {
            if (res.code === 1) {
              this.$message({
                type: "success",
                message: "删除成功!",
              })
              this.handleSearch()
            }
          })
        })
        .catch(() => {})
    },

    // 查询
    handleFormSearch(form) {
      this.pageIndex = 1
      this.handleSearch(form)
    },
    handleSearch(form) {
      this.cacheForm = Object.assign(this.cacheForm, form)
      this.listLoading = true
      const params = Object.assign({}, this.cacheForm)
      for (let key in params) {
        if (params[key] === "") {
          delete params[key]
        }
      }
      params.current = this.pageIndex
      params.size = this.pageSize
      getFeignFieldPage(params).then((res) => {
        this.listLoading = false
        if (res.code === 1) {
          const d = res.data
          this.tableData = d.records || []
          this.total = Number(d.total)
        }
      })
    },
  },
  created() {
    this.handleFormSearch()
    this.getCoopGroupList()
  },
}
</script>

<style lang="scss" scoped>
.drawer__container {
  padding: 0 20px;
  .drawer__content {
    height: calc(100vh - #{"160px"});
    overflow-y: auto;
    &::-webkit-scrollbar {
      width: 0px;
      height: 0px;
    }
    &::-webkit-scrollbar-thumb {
      background-color: #fff;
    }
  }
  .footer {
    margin-top: 20px;
    display: flex;
    button {
      flex: 1;
    }
  }
}
</style>
