<template>
  <div>
    <el-drawer class="custom-drawer-form" :title="title" size="1000px" :visible.sync="drawer" direction="rtl"
      :before-close="close" destroy-on-close>
      <el-container>
        <el-header style="display:flex;align-items:center;justify-content: space-between;">
          <!-- 检索 -->
          <div>
            <el-form :inline="true" class="margin-left_20">
              <el-form-item label="名称">
                <el-input v-model="queryParams.name" size="small" placeholder="请输入名称"></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" size="small" @click="getList">查询</el-button>
              </el-form-item>
            </el-form>
            <!-- 后端没有根据检索式检索 -->
            <!-- <mySearch style="width: 500px" :SearchFields="searchFiled" @search="search" :searchValue="searchOption">
            </mySearch> -->
          </div>
          <el-button type="primary" size="small" @click="handleMerge">合并</el-button>
        </el-header>
        <el-main class="container-common-main">
          <!-- <el-table v-loading="loading" :data="tableData" border header-row-class-name="custom-table-header"
            v-el-table-infinite-scroll="getList" :infinite-scroll-distance="10" :infinite-scroll-disabled="disabled"> -->
          <el-table v-loading="loading" :data="tableData" border header-row-class-name="custom-table-header">
            <el-table-column align="center" width="60">
              <template slot-scope="scope">
                <el-checkbox @change="onChange(scope.row)" v-if="refresh"
                  :checked="mergedList.indexOf(scope.row.name) !== -1"></el-checkbox>
              </template>
            </el-table-column>
            <el-table-column prop="name" label="名称" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="address" label="地址" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column prop="remark" label="备注" align="center" show-overflow-tooltip></el-table-column>
            <el-table-column label="操作" align="center" width="100">
              <template slot-scope="scope">
                <el-button v-if="scope.row.mergeId" type="primary" size="small"
                  @click="handleEdit(scope.row)">编辑</el-button>
              </template>
            </el-table-column>
          </el-table>
          <div class="pagination" style="margin-top: 20px;">
            <el-pagination :current-page.sync="queryParams.pageNum" :page-size="queryParams.pageSize" :total="total"
              @current-change="handleCurrentChange" layout="total, prev, pager, next, jumper" background></el-pagination>
          </div>
        </el-main>
        <el-footer class="footer-common">
          <el-button @click="close">关 闭</el-button>
        </el-footer>
      </el-container>
    </el-drawer>

    <el-dialog :title="mergeTitle" :visible.sync="visible" width="500px" append-to-body destroy-on-close
      :before-close="closeDialog" top="3vh">
      <div class="patent-applicant-merge-select">
        <template v-if="ruleForm.id">
          <el-divider content-position="left">基本信息</el-divider>
          <div style="display:flex;justify-content: flex-end;margin: 10px 0 10px 0px;">
            <el-button type="primary" size="small" @click="handleSave">保存</el-button>
          </div>
        </template>
        <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="80px">
          <el-form-item label="名称" prop="name">
            <el-input v-model="ruleForm.name" placeholder="请输入名称"></el-input>
          </el-form-item>
          <template v-if="mergeType == 0">
            <el-form-item label="简称" prop="abbreviation">
              <el-input v-model="ruleForm.abbreviation" placeholder="请输入名称"></el-input>
            </el-form-item>
            <el-form-item label="国家" prop="country">
              <el-select v-model="ruleForm.country" placeholder="请选择" filterable class="width_100">
                <el-option v-for="(item, index) in commonData" :label="item.label" :key="index"
                  :value="item.label"></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="地址" prop="province">
              <el-cascader ref="myCascader" @change="changeCas" v-model="ruleForm.provinceOld" :options="areaOptions"
                class="width_100"></el-cascader>
            </el-form-item>
          </template>
          <el-form-item label="详细地址" prop="address">
            <el-input v-model="ruleForm.address" placeholder="请输入地址"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="ruleForm.remark" placeholder="请输入备注" type="textarea"></el-input>
          </el-form-item>
        </el-form>
        <template v-if="ruleForm.id">
          <div style="margin: 20px 0px;">
            <el-divider content-position="left">合并信息</el-divider>
          </div>
          <el-table :data="ruleForm.mergedName" border header-row-class-name="custom-table-header">
            <el-table-column prop="name" label="合并人名称" align="center" show-overflow-tooltip>
              <template slot-scope="scope">
                <div>
                  {{ scope.row }}
                </div>
              </template>
            </el-table-column>
            <!-- <el-table-column prop="country" label="国家" align="center" width="150"
              show-overflow-tooltip></el-table-column>
            <el-table-column prop="address" label="地址" align="center" show-overflow-tooltip></el-table-column> -->
            <el-table-column label="操作" align="center">
              <template slot-scope="scope">
                <el-link type="danger" @click="handleDelete(scope.row)">移除</el-link>
              </template>
            </el-table-column>
          </el-table>
        </template>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">关 闭</el-button>
        <el-button v-if="!ruleForm.id" type="primary" @click="handleSave">确认</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
export default {
  components: {
  },
  props: {
    projectId: '',
  },
  data() {
    return {
      // 抽屉标题
      title: '',
      // 控制抽屉开关
      drawer: false,
      // 查询表格的loading
      loading: false,
      // 表格的数据源
      tableData: [],
      // 存放勾选的值的数据(已合并的)
      mergedData: {},
      mergedList: [],
      //检索字段
      searchFiled: [
        {
          label: '名称',
          value: 'name',
          type: 'String',
        }
      ],
      //检索条件
      searchOption: {},
      //禁用懒加载
      disabled: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 总条数
      total: 0,
      // 判断是2发明人还是0申请人与权利人
      mergeType: null,
      // 刷新
      refresh: true,
      /**编辑合并人及基本信息 start*/
      // 控制弹窗开关
      visible: false,
      // 弹窗的title
      mergeTitle: '',
      // 基本信息的数据
      ruleForm: {},
      // 校验
      rules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' },],
      },
      // 国家
      commonData: {},
      // 省市区地址
      areaOptions: [],
      // 合并信息的数据源
      // mergeTable: [],
      // 国家
      commonData: {},
      // 地区
      areaTree: [],
      /**编辑合并人及基本信息 end*/

    }
  },
  mounted() {

  },
  methods: {
    changeCas(val) {
      this.ruleForm.province = this.$refs.myCascader.getCheckedNodes()[0].pathLabels[0]
    },
    // 移除合并人员 
    handleDelete(row) {
      let params = {
        projectId: this.projectId,
        name: this.ruleForm.name,
        delName: row,
        type: this.mergeType,
      }
      this.$confirm('此操作将删除该人员, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.$api.delMergedName(params).then(res => {
          if (res.code == 200) {
            this.$message.success('移除人员成功')
            this.$emit('close')

            let index = this.ruleForm.mergedName.findIndex(item => {
              return item == row
            })
            if (index != -1) {
              this.ruleForm.mergedName.splice(index, 1)
            }
            // this.getMerge(this.ruleForm)
          }
        })
      }).catch(() => {
        this.$message.info('已取消操作');
      });

    },
    // 查询合并的数据
    getMerge(row) {
      let params = {
        projectId: this.projectId,
        id: row.mergeId,
        type: this.mergeType,
      }
      this.$api.selectMergePersonDetail(params).then(res => {
        if (res.code == 200) {
          this.ruleForm = res.data
          this.getShowProvince()
        }
      })
    },
    // 获取省市区并显示
    getShowProvince() {
      if (this.ruleForm.province) {
        let obj = this.areaOptions.find(item => {
          return item.label == this.ruleForm.province
        })
        this.ruleForm.provinceOld = [obj.value]
      }
    },
    // 编辑合并的信息
    handleEdit(row) {
      this.getMerge(row)
      this.mergeTitle = '编辑合并'
      this.visible = true
    },
    // 关闭弹窗
    closeDialog() {
      this.$refs.ruleForm.resetFields()
      // if (this.ruleForm.needMergedName && this.ruleForm.needMergedName.length == 0) {
      if (this.ruleForm.id) {
        this.ruleForm = {
          needMergedName: [],
          mergedName: [],
        }
        this.$set(this, 'mergedList', [])
        this.refresh = false
        this.$nextTick(() => {
          this.refresh = true
        })
      }
      this.visible = false
    },
    // 弹窗中的完成和保存事件
    handleSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.ruleForm.projectId = this.projectId
          this.ruleForm.type = this.mergeType
          // if (this.title.indexOf('新增') != -1) {//新增
          if (this.ruleForm.needMergedName && this.ruleForm.needMergedName.length == 0) {//新增
            // this.ruleForm.mergedName = this.mergedName
            this.$api.mergePerson(this.ruleForm).then(res => {
              if (res.code == 200) {
                this.$message.success('合并成功')
                this.$emit('close')
                this.mergedList = []
                this.closeDialog()
                this.close()
                this.getList()
              }
            })
          } else {
            if (this.ruleForm.needMergedName && this.ruleForm.needMergedName.length > 0) {//
              this.$api.mergePersonAgain(this.ruleForm).then(res => {
                if (res.code == 200) {
                  this.$message.success('编辑成功')
                  this.$emit('close')
                  this.closeDialog()
                  this.close()
                  this.getList()
                }
              })
            } else {
              this.$api.updateMergePerson(this.ruleForm).then(res => {
                if (res.code == 200) {
                  this.$message.success('编辑成功')
                  this.$emit('close')
                  this.closeDialog()
                  this.close()
                  this.getList()

                }
              })
            }
          }
        }
      })
    },
    onChange(row) {
      const index = this.mergedList.indexOf(row.name)
      if (index === -1) {
        this.mergedList.push(row.name)
      } else {
        this.mergedList.splice(index, 1)
      }
      if (row.mergeId) {//已合并过的名称
        const index2 = this.ruleForm.needMergedName.indexOf(row.name)
        if (index2 === -1) {
          this.ruleForm.needMergedName.push(row.name)
        } else {
          this.ruleForm.needMergedName.splice(index, 1)
        }
        for (let k in row) {
          this.$set(this.mergedData, [k], row[k])
        }
      } else {//未合并的名称
        const index3 = this.ruleForm.mergedName.indexOf(row.name)
        if (index3 === -1) {
          this.ruleForm.mergedName.push(row.name)
        } else {
          this.ruleForm.mergedName.splice(index, 1)
        }
      }
    },
    // 合并事件
    handleMerge() {
      if (this.mergedList.length === 0) {
        let text = this.mergeType == 2 ? '请选择发明人' : '请选择申请人/权利人'
        this.$message.error(text)
        return false
      }

      // if (this.title.indexOf('新增') != -1) {//新增
      if (this.ruleForm.needMergedName && this.ruleForm.needMergedName.length > 0) {//编辑直接合并，不填写信息

        this.mergeTitle = '编辑合并'
        if (this.ruleForm.needMergedName.length > 0) {
          for (let k in this.mergedData) {
            this.$set(this.ruleForm, [k], this.mergedData[k])
          }
          this.getShowProvince()
        } else {
          for (let k in this.mergedData) {
            this.$set(this.ruleForm, [k], '')
          }
        }
        this.visible = true
      } else {//新增
        this.ruleForm.id = null
        this.mergeTitle = '新增合并'
        this.visible = true
      }
    },
    // 打开抽屉
    open(row, title) {
      this.mergeType = row.mergeType
      this.title = title
      this.ruleForm.needMergedName = [],
        this.ruleForm.mergedName = [],
        this.getList()
      this.drawer = true
      // 获取国家和地区的数据
      if (this.mergeType == 0) {
        this.getAllCountry()
        this.getAreaList()
      }
    },
    //获取检索条件检索
    search(val) {
      let params = {}
      val.forEach(item => {
        if (item.type == 3) {
          params[item.value] = item.searchValue.map(itemValue => {
            return itemValue.value
          })
        } else {
          params[item.value] = item.searchValue.label
        }
      })
      // 返回条件对象
      this.searchOption = this.$commonJS.ArrayToArray(val)
      // 调用查询接口
      this.queryParams.current = 1
      this.getList()
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
    // 获取发明人或者申请人、权利人数据，包括已合并的数据
    getList() {
      let params = {
        ...this.queryParams,//分页信息
        searchQuery: this.$commonJS.objectToString(this.searchOption || {}),//检索条件
        projectId: this.projectId,//项目id
        type: this.mergeType,
      }
      this.$api.getMergePerson(params).then(res => {
        if (res.code == 200) {
          this.tableData = res.data.data
          this.total = res.data.total
          this.refresh = false
          this.$nextTick(() => {
            this.refresh = true
          })
        }
      }).catch(error => {
        this.tableData = []
        this.total = 0
      })
    },
    // 关闭抽屉
    close() {
      this.ruleForm = {
        needMergedName: [],
        mergedName: [],
      }
      this.mergedList = []
      this.drawer = false
    },
    // 获取国家和地区
    getAllCountry() {
      this.$api.getAllCountry().then(response => {
        this.commonData = response.data
      })
    },
    // 获取中国所有地区(省、自治区、特别行政区)
    getAreaList() {
      this.$api.getAllProvince().then(response => {
        this.areaOptions = response.data
      })
    },
  },
}
</script>

<style lang="scss" scoped></style>