<template>
  <div>
    <el-dialog :title="title" :visible.sync="dialogVisible" width="850px" :before-close="handleClose">
      <el-form :model="form" status-icon :rules="rules" ref="form" label-width="120px" class="demo-ruleForm">
        <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="name" v-SelectLazyLoading="load"
                  :fetch-suggestions="querySearchQuestion" placeholder="请选择研发项目编号" :trigger-on-focus="false"
                  style="width: 100%;">
                </el-autocomplete>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="编号名称：" prop="rdName">
                <el-input v-model="form.rdName" placeholder="请输入研发项目名称"></el-input>
              </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-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" inactive-color="#ff4949">
              </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>
        <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 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>
        <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>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="handleClose">取 消</el-button>
        <el-button type="primary" @click="submit">确 定</el-button>
      </span>
    </el-dialog>

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

<script>
import choosePerson from '@/views/components/dialog/person.vue'
export default {
  components: {
    choosePerson,
  },
  props: {},
  data() {
    return {
      dialogVisible: false,
      title: '',
      form: {
        matterIds: [],
        systemFileList: [],
        fileGuids: [],
      },
      rules: {
        name: [{ required: true, message: '请输入项目名称', trigger: 'blur' },],
      },
      options: [],//负责人数组
      value: '',//负责人
      //人员列表懒加载
      personnelList: {
        queryParams: {
          current: 1,
          size: 10
        },
        data: []
      },
      // 研发编号列表懒加载
      rdNumberArr: {
        queryParams: {
          current: 1,
          size: 10,
        },
        eventInput: '',
        data: []
      },
      //事件列表
      eventList: {
        queryParams: {
          current: 1,
          size: 10
        },
        data: []
      },
      // 控制调查类型是否显示
      show: false,
      //调查类型列表
      dictAssociates: [],
    };
  },
  watch: {},
  computed: {},
  created() { },
  mounted() {
    // 获取人员列表
    this.getPermissionPersonnel();
  },
  methods: {
    //打开事件弹窗
    addEvent() {

    },
    //懒加载事件
    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()
    },
    //获取事件列表
    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 = { name: this.rdNumberArr.eventInput }
      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.eventInput = queryString
      this.rdNumberArr.data = []
      this.rdNumberArr.cb = cb
      await this.getRdProjectByNumber()
    },
    // 人员列表远程搜索
    remoteMethodPerson(query) {
      this.personnelList.data = []
      this.personnelList.queryParams.current = 1
      this.personnelList.queryParams.name = query
      this.getPermissionPersonnel()
    },
    // 获取所有人员列表懒加载
    lazyLoadingPerson() {
      if (this.personnelList.queryParams.current * this.personnelList.queryParams.size >= this.personnelList.queryParams.total) {
        return false
      }
      this.personnelList.queryParams.current += 1
      this.getPermissionPersonnel()
    },
    //获取所有人员列表（修改不要一次性获取，可以使用懒加载加远程搜索 ）
    async getPermissionPersonnel(type) {
      this.personnelList.loading = true;
      await this.$api.getPermissionPersonnel(this.personnelList.queryParams).then((response) => {
        if (response.code == 200) {
          this.personnelList.loading = false;
          if (!type) {
            if (this.form.headId) {
              var index = response.data.findIndex(item => {
                return item.id == this.form.headId
              })
              if (index != -1) {
                response.data.splice(index, 1)
              }
            }
            this.personnelList.queryParams.total = response.pageColumn.total
          }
          this.personnelList.data.push(...response.data)
          // this.personnelList.queryParams.total = response.pageColumn.total
        }
      })
    },
    // 上传的文件监听
    onchangeFile(file, fileList) {
      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)
          this.form.fileGuids.push(file.guid)
        }
      } else {
        this.form.systemFileList.push(file.raw)
      }

    },
    // 删除上传的文件
    onRemove(file, fileList) {
      if (file.guid) {
        let index = this.form.systemFileList.findIndex(item => {
          return item.guid == file.guid
        })
        if (index!=-1) {
          this.form.systemFileList.splice(index, 1)
        }
        let index2 = this.form.fileGuids.findIndex(item => {
            return item == file.guid
        })
        if (index2 != -1) {
            this.form.fileGuids.splice(index2, 1)
        }
      } else {
        let index3 = this.form.systemFileList.findIndex(item => {
          return item.uid == file.uid
        })
        if (index3 != -1) { 
          this.form.fileGuids.splice(index3, 1)
        }
      }
    },
    //打开弹窗
    async open(form) {
      if (form && form.id) {
        this.form = JSON.parse(JSON.stringify(form))
        // 事件
        if (this.form.eventIds && this.form.eventIds.length > 0) {
          this.form.eventId = this.form.eventIds[0]
          this.onChange()
          this.eventList.queryParams.id = this.form.eventId[0]
          await this.getEventList(1)
          this.eventList.queryParams.id = null
          this.show = true
        } else {
          this.show = false
        }
        // 文件
        if (this.form.systemFileList && this.form.systemFileList.length > 0) {
          this.$set(this.form, 'fileGuids', [])
          this.form.systemFileList.forEach(item => {
            this.form.fileGuids.push(item.guid)
          })
        }
        // 负责人
        if (this.form.headId) {
          this.personnelList.queryParams.id = this.form.headId
          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.title = '新增专利挖掘项目'
      }
      this.getPermissionPersonnel()
      this.getEventList()
      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) {
          // 判断文件是否全部上传完毕
          if ((this.form.fileGuids && this.form.fileGuids.length) != (this.form.systemFileList && this.form.systemFileList.length)) {
            this.$message.error('您有文件未上传完毕，请您稍等片刻~~~')
            return false
          }
          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 = []
            this.form.matterIds.forEach(item => {
              this.form.events.push(
                {
                  matterId: item,
                  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', true)
                  this.handleClose()
                }
              })
            }

          } else {//编辑
            this.$api.updatePatentDigProject(this.form).then(res => {
              if (res.code == 200) {
                this.$message.success('更新专利挖掘项目成功')
                this.$emit('isSuccess', true)
                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.current=1
  },
};
</script>
<style lang="scss" scoped></style>