<template>
  <div class="app-container row-container">
    <!--工具栏-->
    <div class="head-container">
      <div class="head-search">
        <!-- 搜索 -->
        <el-input v-model="query.ruleName" clearable size="small" placeholder="输入规则名称搜索" prefix-icon="el-icon-search" style="width: 200px;" class="filter-item" @keyup.enter.native="crud.toQuery" />
        <!-- @input="changePid" -->
        <treeselect
          v-model="query.documentId"
          :options="documentTree"
          style="width: 320px;"
          flat
          :multiple="false"
          :normalizer="normalizer"
          placeholder="请选择源分类（文件库分类）"
        />
        <treeselect
          v-model="query.categoryId"
          :options="categoryTree"
          style="width: 320px;"
          flat
          :multiple="false"
          :normalizer="normalizer"
          placeholder="请选择目标门类（整理库/管理库门类）"
        />
        <rrOperation />
      </div>
      <crudOperation :permission="permission">
        <template v-slot:middle>
          <el-button size="mini" :disabled="crud.selections.length !== 1" @click="toEdit(crud.selections[0])">
            <i class="iconfont icon-bianji" />
            编辑
          </el-button>
        </template>
        <template v-slot:right>
          <el-button :loading="crud.downloadLoading" size="mini" :disabled="crud.selections.length === 0" @click="doExport(crud.selections)">
            <i class="iconfont icon-daochu" />
            导出
          </el-button>
        </template>
      </crudOperation>
    </div>
    <!--表单渲染-->
    <el-dialog class="dialog-middle" append-to-body :close-on-click-modal="false" :before-close="crud.cancelCU" :visible.sync="crud.status.cu > 0" title="新增对应">
      <div class="setting-dialog">
        <el-form ref="form" :inline="true" :model="form" :rules="rules" size="small" label-width="80px">
          <el-form-item label="源分类" prop="documentId">
            <treeselect
              v-model="form.documentId"
              :options="documentTree"
              style="width: 400px;"
              flat
              :multiple="false"
              :normalizer="normalizer"
              placeholder="请选择源分类（文件库分类）"
              @select="handleSelectDocument"
            />
          </el-form-item>
          <el-form-item label="目标门类" prop="categoryId">
            <treeselect
              v-model="form.categoryId"
              :options="categoryTree"
              style="width: 400px;"
              flat
              :multiple="false"
              :normalizer="normalizer"
              placeholder="请选择目标门类（整理库/管理库门类）"
              @select="handleSelectCategory"
            />
          </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
          <el-button type="text" @click="crud.cancelCU">取消</el-button>
          <el-button :loading="crud.status.cu === 2" type="primary" @click="toCorresForm('form')">确定</el-button>
        </div>
      </div>
    </el-dialog>
    <eForm ref="corresForm" />
    <DetailModule ref="detail" />
    <!--表格渲染-->
    <div class="container-wrap">
      <span class="right-top-line" />
      <span class="left-bottom-line" />
      <el-table
        ref="table"
        v-loading="crud.loading"
        :data="crud.data"
        row-key="id"
        @select="crud.selectChange"
        @select-all="crud.selectAllChange"
        @selection-change="crud.selectionChangeHandler"
        @cell-dblclick="tableDoubleClick"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column :show-overflow-tooltip="true" prop="rule_name" label="规则名称" />
        <el-table-column :show-overflow-tooltip="true" prop="documentName" label="源分类（文件库-文件表）" />
        <el-table-column :show-overflow-tooltip="true" prop="categoryName" label=" 目标门类（整理库/管理库-文件表）" />
        <el-table-column :show-overflow-tooltip="true" prop="mate_num" label="已对应字段数量" />
        <el-table-column prop="create_time" label="创建日期" width="200px">
          <template slot-scope="scope">
            <div>{{ scope.row.create_time | parseTime }}</div>
          </template>
        </el-table-column>
      </el-table>
    </div>
  </div>
</template>

<script>
// 获取文件库树
import { FetchDocumentMenu, FetchInitDocumentFieldByPid, FetchInitDocumentField } from '@/api/system/fileLibrary/fileLibrary'
// 获取档案门类树
import { FetchCategoryMenu, FetchInitCategoryFieldByPid, FetchInitCategoryField } from '@/api/system/category/category'
import crudFieldMate from '@/api/system/fieldMate'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
// import { LOAD_CHILDREN_OPTIONS } from '@riophae/vue-treeselect'
import CRUD, { presenter, header, form, crud } from '@crud/crud'
import rrOperation from '@crud/RR.operation'
import crudOperation from '@crud/CRUD.operation'
import eForm from './module/form'
import DetailModule from './module/detail'
import { exportFile } from '@/utils/index'
import qs from 'qs'
import { mapGetters } from 'vuex'

// crud交由presenter持有
const defaultForm = { documentId: null, categoryId: null }
export default {
  name: 'FieldCorresManage',
  components: { crudOperation, rrOperation, Treeselect, eForm, DetailModule },
  cruds() {
    return CRUD({
      title: '对应关系',
      url: 'api/fieldMate/initFieldMateList',
      crudMethod: { ...crudFieldMate },
      optShow: {
        add: true,
        edit: false,
        del: true,
        reset: false,
        download: false,
        group: false
      }
    })
  },
  mixins: [presenter(), header(), form(defaultForm), crud()],
  data() {
    return {
      permission: {
        add: ['admin', 'fieldMate:add'],
        edit: ['admin', 'fieldMate:edit'],
        del: ['admin', 'fieldMate:del']
      },
      categoryTree: [],
      documentTree: [],
      selectedCategoryName: null,
      selectedDocumentName: null,
      rules: {
        documentId: [
          { required: true, message: '请选择源分类（文件库分类）', trigger: 'input' }
        ],
        categoryId: [
          { required: true, message: '请选择目标门类（整理库/管理库门类）', trigger: 'input' }
        ]
      }
    }
  },
  computed: {
    ...mapGetters([
      'baseApi'
    ])
  },
  created() {
    this.getCategoryDataTree()
    this.getDocumentDataTree()
  },
  methods: {
    filterData(data) {
      return data.filter(node => {
        if (node.children && node.children.length > 0) {
          node.children = this.filterData(node.children) // 递归处理子节点
        }
        return node.isType !== 3 // 过滤掉isType为3的节点
      })
    },
    getCategoryDataTree() {
      FetchCategoryMenu().then(res => {
        this.categoryTree = this.filterData(res)
      })
    },
    getDocumentDataTree() {
      FetchDocumentMenu().then(res => {
        this.documentTree = this.filterData(res)
      })
    },
    handleSelectCategory(val) {
      this.selectedCategoryName = val.cnName
    },
    handleSelectDocument(val) {
      this.selectedDocumentName = val.cnName
    },
    toCorresForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          crudFieldMate.FetchCheckRepeat(this.form).then((res) => {
            this.initFiledList(this.form.documentId, this.form.categoryId)
            if (JSON.stringify(res) === JSON.stringify({})) {
              // 不存在对应关系时
              this.$refs.corresForm.corresVisible = true
              this.$refs.corresForm.title = '新增对应关系'
              this.$refs.corresForm.documentName = null
              this.$refs.corresForm.cuform.documentId = this.form.documentId
              this.$refs.corresForm.categoryName = this.selectedCategoryName
              this.$refs.corresForm.cuform.categoryId = this.form.categoryId
            } else {
              // 存在对应关系时
              this.$confirm('当前所选存在对应关系，点击继续会进入编辑操作' + this.crud.title + '<span>你是否还要继续？</span>', '提示', {
                confirmButtonText: '继续',
                cancelButtonText: '取消',
                type: 'warning',
                dangerouslyUseHTMLString: true
              }).then(() => {
                this.$refs.corresForm.title = '编辑对应关系'
                this.$refs.corresForm.corresVisible = true
                this.editGetMate(res.id)
              }).catch((err) => {
                console.log(err)
              })
            }
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 根据pid获取门类字段
    initFiledList(documentId, categoryId) {
      this.$refs.corresForm.selectStatus = []
      this.$refs.corresForm.leftLoading = true
      this.$refs.corresForm.rightLoading = true
      // 文件库字段
      FetchInitDocumentFieldByPid({ documentId: documentId, isType: 2 }).then((res) => {
        this.$refs.corresForm.options = res.sort((a, b) => {
          if (a.isInput !== b.isInput) {
            return a.isInput ? -1 : 1
          } else {
            return a.isSequence - b.isSequence
          }
        })
        this.$refs.corresForm.leftLoading = false
      })
      // 门类字段
      FetchInitCategoryFieldByPid({ categoryId: categoryId, isType: 2 }).then((res) => {
        this.$refs.corresForm.targetData = res.sort((a, b) => {
          if (a.isInput !== b.isInput) {
            return a.isInput ? -1 : 1
          } else {
            return a.isSequence - b.isSequence
          }
        })
        res.forEach((item, index) => {
          this.$refs.corresForm.selectStatus.push({ mode: true, value: '', field: item, isInput: item.isInput })
        })
        this.$refs.corresForm.rightLoading = false
      })
    },
    // table - 双击查看详情
    tableDoubleClick(row) {
      this.getInitDetail(row.id)
    },
    getInitDetail(id) {
      crudFieldMate.FetchInitFieldMate({ 'id': id }).then((res) => {
        this.$refs.detail.detailVisible = true
        this.$refs.detail.detailData = res
      }).catch(err => {
        console.log(err)
      })
    },
    toEdit(row) {
      this.$refs.corresForm.leftLoading = true
      this.$refs.corresForm.rightLoading = true
      this.$refs.corresForm.selectStatus = []
      FetchInitDocumentField({ documentId: row.document_id, isType: 2 }).then((res) => {
        this.$refs.corresForm.options = res.sort((a, b) => {
          if (a.isInput !== b.isInput) {
            return a.isInput ? -1 : 1
          } else {
            return a.isSequence - b.isSequence
          }
        })
        this.$refs.corresForm.leftLoading = false
        this.$nextTick(() => {
          this.$refs.corresForm.title = '编辑对应关系'
          this.$refs.corresForm.corresVisible = true
          this.$nextTick(() => {
            this.editGetMate(row.id)
          })
        })
      })
      // 门类字段
      FetchInitCategoryField({ categoryId: row.category_id, isType: 2 }).then((res) => {
        this.$refs.corresForm.targetData = res.sort((a, b) => {
          if (a.isInput !== b.isInput) {
            return a.isInput ? -1 : 1
          } else {
            return a.isSequence - b.isSequence
          }
        })
        res.forEach((item, index) => {
          this.$refs.corresForm.selectStatus.push({ mode: true, value: '', field: item, isInput: item.isInput })
        })
        this.$refs.corresForm.rightLoading = false
      })
    },
    editGetMate(id) {
      crudFieldMate.FetchInitFieldMate({ id: id }).then((res) => {
        this.$refs.corresForm.cuform.id = res.id
        this.$refs.corresForm.cuform.ruleName = res.ruleName
        this.$refs.corresForm.documentName = res.documentName
        this.$refs.corresForm.categoryName = res.categoryName
        this.$refs.corresForm.cuform.documentId = res.fieldMateDetails[0].pid.documentId.pid
        this.$refs.corresForm.cuform.categoryId = res.fieldMateDetails[0].pid.categoryId.pid
        const getIndexByCategory = (categoryFieldId) => {
          return this.$refs.corresForm.targetData.findIndex(item => item.fieldCnName === categoryFieldId)
        }
        res.fieldMateDetails.map(item => {
          const index = getIndexByCategory(item.categoryFieldId.fieldCnName)
          this.$refs.corresForm.selectStatus.splice(index, 1, { mode: false, value: item.documentFieldId.fieldCnName, field: item.documentFieldId, isInput: item.documentFieldId.isInput })
        })
      }).catch(err => {
        console.log(err)
      })
    },
    doExport(data) {
      console.log(data)
      crud.downloadLoading = true
      this.$confirm('此操作将导出所选数据' + '<span>你是否还要继续？</span>', '提示', {
        confirmButtonText: '继续',
        cancelButtonText: '取消',
        type: 'warning',
        dangerouslyUseHTMLString: true
      }).then(() => {
        const ids = []
        data.forEach(val => {
          ids.push(val.id)
        })
        const params = {
          'fieldMates': ids
        }
        exportFile(this.baseApi + '/api/fieldMate/download?' + qs.stringify(params, { indices: false }))
      }).catch(() => {
      })
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.cnName,
        children: node.children,
        isDisabled: node.isType !== 2
      }
    }
  }
}
</script>

<style lang="scss" scoped>
.head-search{
  .vue-treeselect{
    font-size: 12px;
  }
}
</style>
