<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="请输入名称" clearable @clear="getList"></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" @sort-change="sortChange">
            <el-table-column align="center" width="60">
              <template slot-scope="scope">
                <el-checkbox @change="(val)=>onChange(val,scope.row)" v-if="refresh"
                  :checked="mergedList.findIndex(item=> item.name == 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" v-if="scope.row.mergeId">
                <el-button  type="text" size="small"
                  @click="handleEdit(scope.row)">编辑</el-button>
                <el-button type="text" size="small"
                  @click="handleDelete1(scope.row)" style="color: red;">删除</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">
        <div  style="margin-bottom:20px">
          <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" :loading="btnLoading" @click="handleSave">保存</el-button>
          </div> -->
        </div>
        <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" @change="changeCountry" 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" v-if="ruleForm.country=='中国'">
              <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 >
          <div style="margin: 20px 0px 0px 0px;">
            <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="addName">新增</el-button>
            </div>
          </div>
          <el-table :data="ruleFormTableData" 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.name }}
                </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)">移除</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" :loading="btnLoading" type="primary" @click="handleSave">确认</el-button> -->
        <el-button :loading="btnLoading" type="primary" @click="handleSave">确认</el-button>
      </div>
    </el-dialog>
    <mergeTableDialog ref="mergeTableDialog" :projectId="projectId" :mergeType="mergeType" @checked="getChecked"></mergeTableDialog>
  </div>
</template>

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

  },
  methods: {
    changeCountry(val){
      if(val != '中国'){
        this.$set(this.ruleForm,'provinceOld','')
      }
    },
    // 表格排序 等后端
    sortChange({ column, prop, order }) {
      let obj = {
        orderBy: prop,
        orderType:order
      }
      this.sort=[obj]
      // this.getList()
    },
    changeCas(val) {
      this.ruleForm.province = this.$refs.myCascader.getCheckedNodes()[0].pathLabels[0]
    },
    // 移除合并人员 
    handleDelete(scope) {
      var row = scope.row
      this.ruleFormTableData.splice(scope.$index, 1)
      if(row.sign){
        if(!this.ruleForm.delMergePersonDTOS){
          this.ruleForm.delMergePersonDTOS = []
        }
        this.ruleForm.delMergePersonDTOS.push(row)
      }

      // let params = {
      //   projectId: this.projectId,
      //   name: this.ruleForm.name,
      //   delName: row.name,
      //   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')
      //       this.hasChange = true
      //       let index = this.ruleForm.mergedName.indexOf(row.name)
      //       if (index != -1) {
      //         this.ruleFormTableData.splice(scope.$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
          var data = this.ruleForm.mergedName
          this.ruleFormTableData = data.map(item=>{
            return {
              name:item,
              sign:true
            }
          })
          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
    },
     // 删除表格数据
     handleDelete1(row) {
      this.$confirm('确认删除本条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        let params = {
          id: row.mergeId,
          type: this.mergeType,
        }
        this.$api.delMergePerson(params).then(response => {
          if (response.code == 200) {
            this.$message.success('删除成功')
            // this.loading = false
            this.getList()
          }
        }).catch(error => {
          this.$message.error('删除失败')
          this.loading = false
        })
      })
    },
    // 关闭弹窗
    closeDialog() {
      this.$refs.ruleForm.resetFields()
      this.visible = false
    },
    clearRuleForm(){
      this.ruleForm = {}
      this.$set(this, 'mergedList', [])
      this.refresh = false
      this.$nextTick(() => {
        this.refresh = true
      })
    },
    //编辑时候添加申请人
    addName(){
      var titles={
        0:'选择申请人/权利人',
        2:'选择发明人'
      }
      var data = this.ruleFormTableData.filter(item=>{
        return !item.sign
      })
      if(this.ruleForm.id){
        var disabled = [
          {
            mergeId:this.ruleForm.id
          }
        ]
      }else{
        var disabled = []
      }
      
      this.$refs.mergeTableDialog.open(titles[this.mergeType],data,disabled)
    },
    getChecked(value){
      var signData = this.ruleFormTableData.filter(item=>{
        return item.sign
      })
      this.ruleFormTableData = signData.concat(value)
    },
    // 弹窗中的完成和保存事件
    handleSave() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.ruleForm.projectId = this.projectId
          this.ruleForm.type = this.mergeType
          this.btnLoading = true
          var api = 'commonMerge'
          var message = {
            success:'',
            error:''
          }
          
          // if(this.ruleFormTableData.length>0){
          //   for(var i =0;i<this.ruleFormTableData.length;i++){
          //     var item = this.ruleFormTableData[i]
          //     if(item.mergeId){
          //       this.ruleForm.needMergedName.push(item.name)
          //     }else{
          //       this.ruleForm.mergedName.push(item.name)
          //     }
          //   }
          // }
          this.ruleForm.mergePersonDTOS = this.ruleFormTableData.filter(item=>{
            return !item.sign
          })
          if(this.ruleForm.id){//编辑
            // api = 'updateMergePerson'
            message = {
              success:'编辑成功',
              error:'编辑失败'
            }
          }else{
            message = {
              success:'合并成功',
              error:'合并失败'
            }
            // if (this.ruleForm.needMergedName && this.ruleForm.needMergedName.length == 0) {//新增
            //   api = 'mergePerson'
            //   message = {
            //     success:'合并成功',
            //     error:'合并失败'
            //   }
            // } else {
            //     api = 'mergePersonAgain'
            //     message = {
            //       success:'合并成功',
            //       error:'合并失败'
            //     }
            // }
          }
          
          this.$api[api](this.ruleForm).then(res => {
              if (res.code == 200) {
                this.$message.success(message.success)
                // this.$emit('close')
                this.hasChange = true
                this.mergedList = []
                this.btnLoading = false
                this.clearRuleForm()
                this.closeDialog()
                this.getList()
              }
            }).catch(error=>{
              this.$message.error(message.error)
              this.btnLoading = false
            })
        }
      })
    },
    onChange(val,row) {
      if (val) {
        this.mergedList.push(row)
      } else {
        var index = this.mergedList.findIndex(item => item.name == row.name)
        if(index!=-1){
         this.mergedList.splice(index, 1) 
        }
      }
    },
    // 合并事件
    handleMerge() {
      if (this.mergedList.length === 0) {
        let text = this.mergeType == 2 ? '请选择发明人' : '请选择申请人/权利人'
        this.$message.error(text)
        return false
      }
      this.mergeTitle = '合并'
      var mergedData = this.mergedList[this.mergedList.length-1]
      // for (let k in mergedData) {
      //   this.$set(this.ruleForm, [k], mergedData[k])
      // }
      this.ruleForm = {
        ...mergedData
      }
      this.getShowProvince()
      this.ruleForm.id = null
      this.ruleFormTableData = this.mergedList
      this.visible = true
    },
    // 打开抽屉
    open(row, title) {
      this.mergeType = row.mergeType
      this.title = title
      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.pageNum = 1
      this.getList()
    },
    handleCurrentChange(val) {
      this.queryParams.pageNum = val;
      this.getList();
    },
 
    //生成字符串
    getString(val){
      var data = []
      if (val.constructor == Object) {
        if (Object.keys(val).length > 0) {
          Object.keys(val).forEach(item => {
            data.push(
              {
                key: item,
                value: val[item]
              }
            )
          })
        } else {
          return ''
        }
      } else if (val.constructor == Array) {
        if (val.length > 0) {
          data = val
        } else {
          return ''
        }
      } else {
        return val
      }
      var str = ''
      data.forEach(item => {
        var value = ''
        if (Array.isArray(item.value)) {
          value = '('
          item.value.forEach((i,index)=>{
            if(/\s/.test(i)){
              value += `"${i}"`
            }else{
              value += i
            }
            if(index!= item.value.length- 1){
              value += ' OR '
            }
          })
          value += ')'
        } else {
          if (item.value) {
            // var values = this.$commonJS.AddQuotationMarks(item.value)
            // value = values.join('')
            value = `(${item.value})`
          } else {
            return
          }
        }
        var str2 = ''
        if(item.key == 'name'){
          if(this.mergeType == 2){
            str2 = 'MINM=(' + value +')'
          }else{
            str2 = '(MATM=(' + value + ') OR MRHM=(' + value +'))'
          }
        }
        
        if (str) {
          str = str + ' AND ' + str2
        } else {
          str = str + str2
        }

      })
      return str
    },
    // 获取发明人或者申请人、权利人数据，包括已合并的数据
    getList() {
      let params = {
        ...this.queryParams,//分页信息
        searchQuery: this.getString(this.searchOption || []),//检索条件
        projectId: this.projectId,//项目id
        type: this.mergeType,
      }
      this.loading = true
      this.$api.getMergePerson(params).then(res => {
        if (res.code == 200) {
          this.tableData = res.data.data
          this.total = res.data.total
          this.loading  =false
          this.refresh = false
          this.$nextTick(() => {
            this.refresh = true
          })
        }
      }).catch(error => {
        this.tableData = []
        this.total = 0
        this.loading  =false
      })
    },
    // 关闭抽屉
    close() {
      this.queryParams ={
        pageNum: 1,
        pageSize: 10,
      },
      this.searchOption = {}
      this.mergedList = []
      if(this.hasChange){
        this.$emit('close')
        this.hasChange = false
      }
      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>