<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="850px" :before-close="handleClose"
      :append-to-body="true" :close-on-click-modal="false">
      <el-form :model="form" status-icon :rules="rules" ref="form" label-width="120px" class="demo-form">
        <template>
          <el-divider content-position="left">挖掘项目</el-divider>
          <el-row>
            <el-col :span="12">
              <el-form-item label="项目名称：" prop="name">
                <el-input v-model="form.name" placeholder="请输入项目名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="技术方向：">
                <el-input v-model="form.technicalDirection" placeholder="请输入技术方向"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <!-- <el-col :span="12">
            <el-form-item label="技术方向：">
              <el-input v-model="form.productPhase" placeholder="请输入产品阶段"></el-input>
            </el-form-item>
          </el-col> -->
            <!-- <el-col :span="12">
            <el-form-item label="产出：">
              <el-input v-model="form.output" placeholder="请输入产出"></el-input>
            </el-form-item>
          </el-col> -->

          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="相关竞争对手：">
                <el-input v-model="form.relatedCompetitors" placeholder="请输入相关竞争对手"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="技术关键词：">
                <el-input v-model="form.technicalKeyword" placeholder="请输入技术关键词"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="预计产出：">
                <el-input v-model="form.output" placeholder="请输入产出"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="是否检索：">
                <el-switch v-model="form.ifSearch" active-color="#13ce66">
                </el-switch>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <!-- <el-form-item label="是否审核：">
              <el-switch v-model="form.examine" active-color="#13ce66" inactive-color="#ff4949">
              </el-switch>
            </el-form-item> -->
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="参与人：">
                <div class="manage">
                  <el-button size="small" @click="showDialog()">选择</el-button>
                  <div v-html="getNames(form.adminPersons)">

                  </div>
                </div>
              </el-form-item>
            </el-col>

          </el-row>
          <template>
            <div>
              <el-row>
                <el-col :span="24">
                  <el-form-item label="事件：">
                    <mySelectButton size='large' style="width:100%" @click="addEvent">
                      <div style="width:100%">
                        <el-select style="width:100%" v-model="form.eventId" @change="changeEvent" filterable remote
                          :disabled="eventList.disabled" clearable placeholder="请选择" :loading="eventList.loading"
                          v-SelectLazyLoading="loadEvent" :remote-method="remoteEvent">
                          <el-option v-for="item in eventList.data" :key="item.id" :label="item.name" :value="item.id">
                          </el-option>
                        </el-select>
                      </div>
                    </mySelectButton>
                  </el-form-item>
                </el-col>
              </el-row>
              <el-row v-if="show == true">
                <el-col :span="24">
                  <el-form-item label="调查类型：" prop="matterIds">
                    <el-checkbox-group v-model="form.matterIds">
                      <template>
                        <el-checkbox v-for="item in dictAssociates" :key="item.id" :label="parseInt(item.id)">
                          {{ item.name }}
                        </el-checkbox>
                      </template>
                    </el-checkbox-group>
                  </el-form-item>
                </el-col>
              </el-row>
            </div>
          </template>

          <el-row>
            <el-col :span="24">
              <template>
                <div>
                  <el-form-item label="委托方" prop="entrustId" v-if="userinfo.tenantType == 1">
                    <mySelectButton size='large' style="width:100%" @click="handleSelect">
                      <div style="width:100%">
                        <el-autocomplete style="width:100%" v-model="form.entrustName" ref="client" value-key="name"
                          :fetch-suggestions="querySearch" v-SelectLazyLoading="loadClient" @input="input"
                          placeholder="请输入内容" :trigger-on-focus="false" @select="handleChange">
                        </el-autocomplete>
                      </div>
                    </mySelectButton>
                  </el-form-item>
                  <el-form-item label="委托部门" prop="entrustId" v-else>
                    <mySelectTree style="width:100%" v-model="form.entrustId" :options="departmentList"></mySelectTree>
                  </el-form-item>
                </div>
              </template>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="负责人：">
                <el-select v-model="form.headId" placeholder="请选择负责人" style="width: 100%;" filterable remote
                  :remote-method="remoteMethodPerson" v-SelectLazyLoading="lazyLoadingPerson"
                  :loading="personnelList.loading">
                  <el-option v-for="item in personnelList.data" :key="item.id" :label="item.name" :value="item.id">
                  </el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="附件：">
                <myUpload :file-list="form.systemFileList" @on-change="onchangeFile" @on-remove="onRemove"
                  style="height: 180px;" :autoUpload="true"></myUpload>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="项目备注：">
                <el-input type="textarea" :rows="3" placeholder="请输入内容" v-model="form.description"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
        <!-- 研发项目 -->
        <template>
          <el-divider content-position="left">研发项目</el-divider>
          <el-row>
            <el-col :span="12">
              <el-form-item label="编号：">
                <el-autocomplete class="inline-input" v-model="form.rdnumber" value-key="number"
                  v-SelectLazyLoading="load" :fetch-suggestions="querySearchQuestion" placeholder="请选择编号"
                  :trigger-on-focus="false" @select="handleRdNumber" @change="changeRdNumber" style="width: 100%;">
                </el-autocomplete>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="项目名称：" prop="rdName">
                <el-autocomplete class="inline-input" v-model="form.rdName" value-key="name"
                  v-SelectLazyLoading="loadRdName" :fetch-suggestions="querySearchRdName" placeholder="请输入研发项目名称"
                  :trigger-on-focus="false" @select="handleRdName" @change="changeRdName" style="width: 100%;">
                </el-autocomplete>
              </el-form-item>
            </el-col>

          </el-row>
          <el-row>
            <el-col :span="12">
              <el-form-item label="产品：" prop="product">
                <el-input v-model="form.product" placeholder="请输入产品名称"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="产品阶段：">
                <el-input v-model="form.productPhase" placeholder="请输入产品阶段"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </template>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" v-if="!form.id" @click="handleExamine">提交审核</el-button>
        <el-button type="primary" @click="submit">直接完成</el-button>
      </span>
    </el-dialog>

    <choosePerson ref="choosePerson" @getPersonIds="getPersonIds"></choosePerson>

    <el-dialog title="选择委托方" :visible.sync="visible" width="800px" append-to-body destroy-on-close :before-close="close2"
      top="10vh">
      <ClientTable :choseClient="true" @getClient="getClient"></ClientTable>
    </el-dialog>

    <examine ref="examine" @save="addProjectOpenExamineTask"></examine>
    <addEvent ref="addEvent"></addEvent>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import { personnelLoading } from '../mixins/index2'
import choosePerson from '@/views/components/dialog/person.vue'
import ClientTable from '@/views/client'
import examine from '@/views/components/dialog/examine.vue'
import addEvent from '@/views/event/components/dialog/addEvent.vue'
export default {
  mixins: [personnelLoading],
  components: {
    choosePerson,
    ClientTable,
    examine,
    addEvent,
  },
  props: {},
  data() {
    return {
      dialogVisible: false,
      title: '',
      form: {
        matterIds: [],
        systemFileList: [],
        fileGuids: [],
        ifSearch: true,
      },
      rules: {
        name: [{ required: true, message: '请输入项目名称', trigger: 'blur' },],
      },
      options: [],//负责人数组
      value: '',//负责人
      //人员列表懒加载
      personnelList: {
        queryParams: {
          current: 1,
          size: 10
        },
        data: []
      },
      // 研发项目编号列表懒加载
      rdNumberArr: {
        queryParams: {
          current: 1,
          size: 10,
        },
        input: '',
        data: []
      },
      // 研发项目名称列表懒加载
      rdNameArr: {
        queryParams: {
          current: 1,
          size: 10,
        },
        input: '',
        data: []
      },
      //事件列表
      eventList: {
        queryParams: {
          current: 1,
          size: 10
        },
        data: []
      },
      /**
       * 委托方
       */
      clientList: {
        queryParams: {
          current: 1,
          size: 10
        },
        data: [],
        cb: null
      },
      visible: false,
      // 控制调查类型是否显示
      show: false,
      //调查类型列表
      dictAssociates: [],
      // 部门数据
      departmentList:[],
    };
  },
  watch: {},
  computed: {
    ...mapGetters(['webSocket', 'userinfo']),
  },
  created() { },
  mounted() {
    // 获取人员列表
    // this.getPermissionPersonnel();
    this.getDepartment()
  },
  methods: {
    //获取部门列表
    getDepartment() {
      this.$api.getPermissionDepartmentList().then((response) => {
        this.departmentList = response.data;
      });
    },
    // 专利挖掘项目审核
    addProjectOpenExamineTask(form) {
      var params = {
        patentDigProjectDTO: this.form,
        projectTaskDTO: form,

      }
      this.$api.addProjectOpenExamineTask(params).then(res => {
        if (res.code == 200) {
          this.$message.success('已发送审核任务')
          this.$emit('isSuccess', '新增成功')
          this.$refs.examine.handleCloseTask()
          this.handleClose()
        }
      })
    },
    /**
    * 0标引任务
    * 1项目开卷审核任务
    * 2检索条件任务
    * 3对比任务
    * 4协同任务
    * 5任务审核任务
    * 
    */
    // 审核任务弹窗
    handleExamine() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          var form = {
            name:this.form.name + '审核任务'
          }
          this.$refs.examine.open(form)
        }
      })
    },
    /**
     * 客户/委托方
     * @param {*} query 
     */
    //远程搜索委托方（建议调取接口获取）
    async querySearch(queryString, cb) {
      this.clientList.queryParams.current = 1
      this.clientList.queryParams.name = queryString
      this.clientList.data = []
      this.clientList.cb = cb
      await this.getClientList()
      // 调用 callback 返回建议列表的数据
      // cb(this.clientList.data);
    },
    loadClient() {
      if (this.clientList.queryParams.current * this.clientList.queryParams.size >= this.clientList.queryParams.total) {
        return false
      }
      this.clientList.queryParams.current += 1
      this.getClientList()
    },
    //获取委托方
    async getClientList() {
      await this.$api.getAdminClientList(this.clientList.queryParams).then(res => {
        if (res.code == 200) {
          this.clientList.data.push(...res.data.records)
          this.clientList.queryParams.total = res.data.total
          this.clientList.cb(this.clientList.data);
        }
      })
    },
    //输入框输入事件（委托方）
    input() {
      this.$set(this.form, 'entrustId', -1)
    },
    //切换选择委托方
    handleChange(row) {
      this.$set(this.form, 'entrustId', row.id)
      this.$set(this.form, 'entrustName', row.name)
      this.close2()
    },
    //打开选择委托方弹窗
    handleSelect() {
      this.visible = true
    },
    //获取委托方信息
    getClient(row) {
      this.$set(this.form, 'entrustId', row.id)
      this.$set(this.form, 'entrustName', row.name)
      this.close2()
    },
    //关闭委托方弹窗
    close2() {
      this.visible = false
    },

    /*
    * 事件
    */
    //打开事件弹窗
    addEvent() {
      let form = {}
      this.$refs.addEvent.open(form, 1)
    },
    //懒加载事件
    loadEvent() {
      if (this.eventList.queryParams.current * this.eventList.queryParams.size >= this.eventList.queryParams.total) {
        return false
      }
      this.eventList.queryParams.current += 1
      this.getEventList()
    },
    //远程搜索
    remoteEvent(query) {
      this.eventList.data = []
      this.eventList.queryParams.current = 1
      this.eventList.name = query
      this.getEventList(1)
    },
    //获取事件列表
    async getEventList(type) {
      this.eventList.loading = true;
      let params = {
        ...this.eventList.queryParams,//分页信息
        searchQuery: this.eventList.name ? `name=${this.eventList.name}` : '',//检索条件
        orderDTOList: [{ orderBy: "createTime", orderType: 1 },]//排序
      }
      await this.$api.queryEvent(params).then(response => {
        if (response.code == 200) {
          this.eventList.loading = false;
          if (!type) {
            if (this.form.eventId) {
              var index = response.data.data.findIndex(item => {
                return item.id == this.form.eventId
              })
              if (index != -1) {
                response.data.data.splice(index, 1)
              }
            }
            this.eventList.queryParams.total = response.data.total
          }
          this.eventList.data.push(...response.data.data)
          // this.eventList.queryParams.total = response.data.total
        }
      })
    },
    //切换事件
    async changeEvent(val) {
      if (!val) {
        this.form.scenarioIds = []
        this.show = false
        this.form.matterIds = []
        return
      }
      var obj = this.eventList.data.find(item => {
        return item.id == val
      })
      if (obj) {
        this.form.scenarioIds = [obj.scenarioId]
        this.show = true
        await this.onChange()
      }
    },

    //调查类型选择切换
    async onChange() {
      if (this.form.scenarioIds.length != 0) {
        await this.$api.getMatter(this.form.scenarioIds).then(response => {
          this.show = true
          this.dictAssociates = response.data.data
        })
      } else {
        this.show = false
      }
    },
    // 打开参与人 人员弹窗
    showDialog() {
      this.$refs.choosePerson.open(this.form.adminIds, this.form.adminPersons)
    },
    //获取参与人员信息
    getPersonIds({ personIds, persons }) {
      if (personIds.length > 0) {
        // adminPersons存储返回的人员id数组
        this.$set(this.form, 'adminPersons', persons)
        this.$set(this.form, 'adminIds', personIds)
      } else {
        this.$set(this.form, 'adminPersons', [])
        this.$set(this.form, 'adminIds', [])
      }
    },
    // 处理参与人数据
    getNames(row) {
      if (!row) {
        return ''
      }
      var arr = row.map(item => {
        return item.name
      })
      return arr.join('、')
    },

    /**
     * 研发编号
     */
    // 研发编号懒加载方法
    load() {
      if (this.rdNumberArr.queryParams.current * this.rdNumberArr.queryParams.size >= this.rdNumberArr.queryParams.total) {
        return false
      }
      this.rdNumberArr.queryParams.current++
      this.getRdProjectByNumber()
    },
    // 查询研发编号
    async getRdProjectByNumber() {
      let searchValue = { number: this.rdNumberArr.input }
      let params = {
        ...this.rdNumberArr.queryParams,//分页信息
        searchQuery: this.$commonJS.objectToString(searchValue)//输入的建议
      }
      await this.$api.getRdProjectByNumber(params).then(res => {
        if (res.code == 200) {
          this.rdNumberArr.data.push(...res.data.data)
          this.rdNumberArr.queryParams.total = res.data.total
          this.rdNumberArr.cb(this.rdNumberArr.data);
        }
      })
    },
    //获取下拉建议研发编号数据
    async querySearchQuestion(queryString, cb) {
      this.rdNumberArr.queryParams.current = 1
      this.rdNumberArr.input = queryString
      this.rdNumberArr.data = []
      this.rdNumberArr.cb = cb
      await this.getRdProjectByNumber()
    },
    // 选中的研发编号
    handleRdNumber(val) {
      this.$set(this.form, 'rdnumber', val.number)
      this.$set(this.form, 'rdName', val.name)
    },
    // 监听研发项目编号输入框的值
    changeRdNumber(val) {
      if (val) {
        this.form.rdnumber = val
        if (this.form.rdName) {
          let a = this.rdNameArr.data.findIndex(item => {
            return item.name == this.form.rdName
          })
          if (a != -1) {
            this.form.rdName = ''
          }
        }
      }
    },

    /**
     * 研发项目名称rdNameArr
     */
    loadRdName() {
      if (this.rdNameArr.queryParams.current * this.rdNameArr.queryParams.size >= this.rdNameArr.queryParams.total) {
        return false
      }
      this.rdNameArr.queryParams.current++
      this.getRdProjectRdName()
    },
    // 查询研发项目名称
    async getRdProjectRdName() {
      let searchValue = { name: this.rdNameArr.input }
      let params = {
        ...this.rdNameArr.queryParams,//分页信息
        searchQuery: this.$commonJS.objectToString(searchValue)//输入的建议
      }
      await this.$api.getRdProjectByNumber(params).then(res => {
        if (res.code == 200) {
          this.rdNameArr.data.push(...res.data.data)
          this.rdNameArr.queryParams.total = res.data.total
          this.rdNameArr.cb(this.rdNameArr.data);
        }
      })
    },
    //获取下拉建议研发项目名称数据
    async querySearchRdName(queryString, cb) {
      this.rdNameArr.queryParams.current = 1
      this.rdNameArr.input = queryString
      this.rdNameArr.data = []
      this.rdNameArr.cb = cb
      await this.getRdProjectRdName()
    },
    // 选中的研发项目名称
    handleRdName(val) {
      this.$set(this.form, 'rdnumber', val.number)
      this.$set(this.form, 'rdName', val.name)
    },
    // 监听研发项目名称输入框的值
    changeRdName(val) {
      if (val) {
        if (this.form.rdnumber) {
          let a = this.rdNumberArr.data.findIndex(item => {
            return item.number == this.form.rdnumber
          })
          if (a != -1) {
            this.form.rdnumber = ''
          }
        }
        this.form.rdName = val
      }
    },


    /**
     * 上传文件处理
     *  */
    // 上传的文件监听
    onchangeFile(file, fileList) {
      if(!this.form.systemFileList){
        this.$set(this.form,'systemFileList',[])
      }
      if (file.guid) {
        let index = this.form.systemFileList.findIndex(item => {
          return item.uid == file.uid
        })
        if (index != -1) {
          this.form.systemFileList.splice(index, 1, file)
        }
      } else {
        this.form.systemFileList.push(file.raw)
      }

    },
    // 删除上传的文件
    onRemove(file, fileList) {
      let index = this.form.systemFileList.findIndex(item => {
        return item.uid == file.uid
      })
      if (index != -1) {
        this.form.systemFileList.splice(index, 1)
      }
    },


    //打开弹窗
    async open(form) {
      this.personnelList.data = []
      if (form && form.id) {
        this.form = JSON.parse(JSON.stringify(form))
        // 负责人
        if (this.form.headId) {
          this.personnelList.queryParams.id = this.form.headId
          await this.getPermissionPersonnel(1)
          this.personnelList.queryParams.id = null
        }
        // 部门委托客户
        if (this.form.entrustId) {
          
          // this.personnelList.queryParams.id = this.form.entrustId
          // await this.getPermissionPersonnel(1)
          // this.personnelList.queryParams.id = null
        }
        // 参与人
        if (this.form.involvedPersons && this.form.involvedPersons.length) {
          this.form.adminPersons = []
          this.form.adminIds = []
          this.form.involvedPersons.forEach(item => {
            let a = {
              id: item.personId,
              name: item.personName
            }
            this.form.adminPersons.push(a)
            this.form.adminIds.push(a.id)
          })
        }
        this.title = '编辑专利挖掘项目'
      } else {
        // this.eventList.disabled = false
        // if (this.form.eventId) {
        //   this.eventList.disabled = true
        //   this.eventList.data.push({
        //     id: this.form.eventId,
        //     name: this.form.eventName,
        //   })
        // }
        this.title = '新增专利挖掘项目'
      }
      this.eventList.data = []
      this.eventList.name = ''
      this.eventList.disabled = false
      var hasEvent = false
      if(this.form.eventId){
        this.eventList.disabled = true
        hasEvent = true
      }
      if(this.form.eventIds){
        this.form.eventId = this.form.eventIds[0]
        hasEvent = true
      }
      if(hasEvent){
        if(this.form.eventId){
          let params = {
            current:1,
            size:1,
            searchQuery:`id=${this.form.eventId}`,//检索条件
            orderDTOList: [
              {
                orderBy: "createTime",
                orderType: 1
              },
            ]//排序
          }
          await this.$api.queryEvent(params).then(response => {
            if(response.code == 200){
              this.eventList.data.push(...response.data.data)
              this.eventList.queryParams.total = response.data.total
            }
          })
          this.changeEvent(this.form.eventId)
        }else{
          this.getEventList()
        }
        
      }
      this.getPermissionPersonnel()
      this.dialogVisible = true
    },
    //关闭弹窗
    handleClose() {
      // this.$refs.upload.clearFiles()
      this.$refs.form.resetFields()
      this.form = {
        matterIds: [],
        systemFileList: [],
        fileGuids: [],
      }
      this.dialogVisible = false
    },
    //提交数据
    submit() {
      this.$refs.form.validate((valid) => {
        if (valid) {
          // 判断文件是否都上传完毕
          this.$commonJS.allUploadFile(this.form)
          if (this.form.scenarioIds && this.form.scenarioIds.length > 0) {
            var scenarioIds = JSON.parse(JSON.stringify(this.form.scenarioIds))
          }
          if (this.form.eventId) {
            this.form.events = []
            this.form.scenarioIds = []
            if(this.form.matterIds.length>0){
              this.form.matterIds.forEach(item => {
                this.form.events.push(
                  {
                    matterId: item,
                    scenarioId: scenarioIds[0],
                    eventId: this.form.eventId
                  }
                )
              })
            }else{
              this.form.events.push(
                  {
                    matterId: null,
                    scenarioId: scenarioIds[0],
                    eventId: this.form.eventId
                  }
                )
            }
            
          }
          if (this.form.adminIds && this.form.adminIds.length > 0) {
            this.form.involvedPersonIds = this.form.adminIds
          }
          if (!this.form.id) {//新增
            if (this.form.examine) {//审核任务

            } else {//不审核直接创建项目
              this.$api.addPatentDigProject(this.form).then(res => {
                if (res.code == 200) {
                  this.$message.success('新增专利挖掘项目成功')
                  this.$emit('isSuccess', '新增成功')
                  this.handleClose()
                }
              }).catch(error => {
                // 如果报告未创建成功，则赋值
                this.form.scenarioIds = JSON.parse(JSON.stringify(scenarioIds))
                this.show = true
              })
            }

          } else {//编辑
            this.$api.updatePatentDigProject(this.form).then(res => {
              if (res.code == 200) {
                this.$message.success('更新专利挖掘项目成功')
                this.$emit('isSuccess', '更新成功')
                this.handleClose()
              }
            })
          }

        } else {
          this.$message.error('信息未输入完整')
        }
      });

    },
    // 审核任务
    examine(data) {
      let params = {

      }
      this.$api.task(params).then(res => {
        if (res.code == 200) {

        }
      })
    },
  },
  // 组件销毁函数
  destroyed() {
    // 清空事件相关
    this.form.eventIds = []
    this.eventList.queryParams.current = 1
    // 清空负责人相关
    this.form.involvedPersons = []
    this.form.adminIds = []
    this.form.adminPersons = []
    this.personnelList.data = []
    this.personnelList.queryParams.name = ''
    this.personnelList.queryParams.current = 1
  },
};
</script>
<style lang="scss" scoped></style>