<template>
  <div>
    <el-dialog :title="title" :visible.sync="showDialog" width="1000px" :close-on-click-modal="false"
      @close="handleClose(false)" :append-to-body="true">
      <el-form :model="form" :rules="rules" ref="reportForm" label-width="120px" v-loading="loading"
        :element-loading-text="load_text" element-loading-spinner="el-icon-loading"
        element-loading-background-color="rgba(0, 0, 0, 0.8)">
        <el-row>
          <el-col :span="12">
            <el-form-item :label="[3].includes(Number(form.type)) ? '标的产品' : '标的专利'" prop="signPatentNo">
              <el-input v-model="form.signPatentNo" autocomplete="off"
                :placeholder="[3].includes(Number(form.type)) ? '请输入标的产品' : '请输入标的专利'" @change="getPatentNo"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报告名称" prop="name">
              <el-input v-model="form.name" autocomplete="off" placeholder="请输入报告名称"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="是否完成" v-if="!form.id">
          <el-switch v-model="form.status" active-color="#13ce66" inactive-color="#ff4949" @change="changeStatus"
            :active-value="3" :inactive-value="1">
          </el-switch>
        </el-form-item>
        <template v-if="!form.id && form.status == 3">
          <div>
            <el-form-item label="核心结论">
              <el-checkbox-group v-model="form.conclusionIds">
                <el-checkbox v-for="item in conclusion" :key="item.dictChildValue" :label="item.dictChildValue">{{
                  item.dictChildLabel }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="结论论述">
              <el-input v-model="form.cronConclusion" type="textarea" placeholder="请输入结论论述"></el-input>
            </el-form-item>
            <el-form-item label="后续跟进事项" v-if="$permission('/rms/matter')">
              <span v-if="form.followUps"><span v-for="item in form.followUps" :key="item.followUpName"
                  style="margin-right:10px">{{ item.followUpName }}</span></span>
              <span>
                <el-popover ref="popover" placement="bottom" @hide="hidePopover" @show="showPopover" trigger="click">
                  <div>
                    <addMatter :type="matterType" :sign="matterSign" @value="getMatter"></addMatter>
                  </div>
                  <el-button slot="reference">添加后续事项</el-button>
                </el-popover>
              </span>
            </el-form-item>
          </div>
        </template>
        <el-row>
          <el-col :span="12">
            <el-form-item label="承担部门" prop="departmentId">
              <mySelectTree style="width:100%" v-model="form.departmentId" :options="departmentList"></mySelectTree>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="personId">
              <el-select style="width:100%" v-model="form.personId" placeholder="请选择负责人" filterable remote
                :popper-append-to-body="false" :remote-method="remoteMethodPerson" v-SelectLazyLoading="lazyLoadingPerson"
                :loading="loading">
                <el-option v-for="item in personnelList" :key="item.id" :label="item.personnelName"
                  :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <template>
              <div>
                <el-form-item label="委托方" prop="clientId" v-if="userinfo.tenantType == 1">
                  <el-select style="width:100%" v-model="form.clientId" placeholder="请选择委托方" filterable remote
                    :popper-append-to-body="false" :remote-method="remoteMethodClient"
                    v-SelectLazyLoading="lazyLoadingClient" :loading="loading">
                    <el-option v-for="item in clientList" :key="item.id" :label="item.name" :value="item.id"></el-option>
                  </el-select>
                </el-form-item>
                <el-form-item label="委托部门" prop="departmentId" v-else>
                  <mySelectTree style="width:100%" v-model="form.departmentId" :options="departmentList"></mySelectTree>
                </el-form-item>
              </div>
            </template>
          </el-col>
          <el-col :span="12">
            <el-form-item label="卷号" prop="volumeNumber">
              <el-input v-model="form.volumeNumber" autocomplete="off" placeholder="请输入卷号"></el-input>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="应用场景">
          <el-checkbox-group v-model="form.scenarioList">
            <el-checkbox v-for="item in commonData.ENTERPRISE_APPLICATION_SCENARIO" :key="item.value"
              :label="parseInt(item.value)">{{ item.label }}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        <el-row>
          <el-col :span="24">
            <el-form-item label="产品/技术">
              <el-input v-model="form.proTec" autocomplete="off" placeholder="请输入产品/技术"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="form.track ? 12 : 24">
            <el-form-item label="关联报告">
              <el-input v-model="form.associateReportName" autocomplete="off" placeholder="请输入关联报告"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="需要复制的选项" v-show="form.track">
              <el-select v-model="form.copyIds" multiple clearable placeholder="请选择需要复制的选项" :popper-append-to-body="false"
                @change="changeCopyIds">
                <el-option v-for="item in copyList" :key="item.dictChildValue" :label="item.dictChildLabel"
                  :value="item.dictChildValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <template v-if="form.type == 7">
          <div>
            <el-row>
              <el-col :span="12">
                <el-form-item label="案件编号">
                  <el-input v-model="form.caseNumber" autocomplete="off" placeholder="请输入案件编号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="发文序号">
                  <el-input v-model="form.issueNumber" autocomplete="off" 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.inventionName" autocomplete="off" placeholder="请输入发明创造名称"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="无效宣告请求人">
                  <el-input v-model="form.invalidApplication" autocomplete="off" placeholder="请输入无效宣告请求人"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </template>
        <el-form-item :label="(!form.id && form.status == 3) ? '上传报告文档' : '上传附件'">
          <myUpload :file-list="handleConcat(form[0].systemFileList)" @on-change="onChange" @on-remove="onRemove"
            @on-preview="onPreview" style="height: 180px;"></myUpload>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input type='textarea' v-model="form.remark" autocomplete="off" placeholder="请输入备注"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" v-if="$reportPermission(form.id, [0, 1])">
        <el-button @click="handleClose(false)">取 消</el-button>
        <el-button type="primary" @click="ifNext" v-if="form.type == 7 && !form.id">下一步</el-button>
        <el-button type="primary" @click="submit" v-else>确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
export default {
  components: {},
  props: {},
  data() {
    const isExist = (rule, value, callback) => {
      if (!this.form.signPatentNo) {//没有专利号进入报错提示
        this.show = 0
        if ([3].includes(Number(this.form.type))) {
          var text = '请输入标的产品'
        } else {
          var text = '请输入标的专利号'
        }
        callback(new Error(text))
      }
    }
    return {
      //弹窗标题
      title: '',
      //控制弹窗是否打开
      showDialog: false,
      //表单数据
      form: {},
      //表单规则
      rules: {
        name: [{ required: true, message: '请输入报告名称', trigger: 'blur' },],
        signPatentNo: [{ required: true, validator: isExist, trigger: 'blur' },],
        personId: [{ required: true, message: '请选择负责人', trigger: 'change' },],
        clientId: [{ required: true, message: '请选择委托方', trigger: 'change' },],
      },
      //加载
      loading: false,
      //加载时显示的文字
      load_text: '加载中',
      //应用场景
      commonData: {},
      //核心结论
      conclusion: [],
      //部门数据
      departmentList: [],
      //需要复制的选项集合
      copyList: [],
      //人员列表
      personnelList: [],
      //客户列表
      clientList: [],
      //上传文件列表
      files: [],
      //核心结论类型字典
      reportAsDicItem: {
        "0": "INVALID_ASSESS",
        "1": "THIRD_ASSESS",
        "2": "STABILITY_ASSESS",
        "3": "FTO_ASSESS",
        "4": "TORT_ASSESS",
        "5": "AVOID_ASSESS",
        "7": "REINVALID_ASSESS",
      },
      //需要复制的内容字典
      reportAsDicItemCopy: {
        "0": "INVALID_COPY",
        "1": "THIRD_COPY",
        "2": "STABILITY_COPY",
        "3": "FTO_COPY",
        "4": "TORT_COPY",
        "5": "AVOID_COPY",
      },
      queryParams: {
        current: 1,
        size: 10,
      },
      //是否懒加载
      isLazy: true,
    };
  },
  watch: {},
  computed: {
    ...mapGetters(['webSocket', 'userinfo']),
    dictMessage() {
      return this.$store.state.dictMessage.dictMessage
    },
  },
  created() { },
  mounted() {
    //获取字典项（接口还是通过字典获取）
    this.$api.getCommonData({ keys: 'QUERY_GROUP,ENTERPRISE_APPLICATION_SCENARIO,INVESTIGATION_TYPE' }).then(response => {
      this.commonData = response.data
    })
    // console.log(1)
    //获取所有人员列表（修改不要一次性获取，可以使用懒加载加远程搜索 ）
    this.getAllPersonnelList()
    //获取所有客户列表（修改不要一次性获取，可以使用懒加载加远程搜索 ）
    this.getAllClientList()
    //获取所有部门列表
    this.getAllDepartmentList()
  },
  methods: {
    //打开弹窗
    open(form) {
      this.form = JSON.parse(JSON.stringify(form))
      var a = ''
      if (this.form.id) {
        if (this.$reportPermission(this.form.id, [0, 1])) {
          a = '编辑'
        } else {
          a = '查看'
        }
      } else {
        a = '创建'
      }
      var reportType = this.dictMessage.REPORT_TYPE.filter(item => { return item.dictChildValue == this.form.type })[0].dictChildLabel
      this.title = a + reportType + '报告'
      this.showDialog = true
    },
    // 人员列表远程搜索
    remoteMethodPerson(query) {
      this.isLazy = true
      if (query !== '') {
        this.loading = true;
        let params = {
          ...this.queryParams,//分页信息
          searchQuery: `name=${query}`,
        }
        this.$api.AllPersonnelList(params).then(response => {
          if (response.code == 200) {
            this.loading = false;
            this.personnelList = response.data.data
          }
        }).catch(error => {
          this.loading = false;
        })
      } else {
        this.personnelList = [];
        this.getProductCategory()
      }
    },
    // 获取所有人员列表懒加载
    lazyLoadingPerson() {
      if (!this.isLazy) {
        return false
      }
      this.queryParams.current++;
      this.getAllPersonnelList();
    },
    //获取所有人员列表（修改不要一次性获取，可以使用懒加载加远程搜索 ）
    getAllPersonnelList() {
      if (!this.isLazy) {
        return false
      }
      let params = {
        ...this.queryParams,//分页信息
      }
      this.$api.AllPersonnelList(params).then(response => {
        if (response.code == 200) {
          if (response.data.data && response.data.data.length == 0) {
            this.isLazy = false
          }
          this.personnelList = [...this.personnelList, ...response.data.data];
        }
      }).catch(error => {
        this.personnelList = []
        this.$message.error(error.message)
      })
    },
    // 客户列表远程搜索
    remoteMethodClient(query) {
      this.isLazy = true
      if (query !== '') {
        this.loading = true;
        let params = {
          ...this.queryParams,//分页信息
          searchQuery: `name=${query}`,
        }
        this.$api.AllClientList(params).then(response => {
          if (response.code == 200) {
            this.loading = false;
            this.clientList = response.data.data
          }
        }).catch(error => {
          this.loading = false;
        })
      } else {
        this.clientList = [];
        this.getAllClientList()
      }
    },
    // 获取所有客户列表懒加载
    lazyLoadingClient() {
      if (!this.isLazy) {
        return false
      }
      this.queryParams.current++;
      this.getAllClientList();
    },
    //获取所有客户列表（修改不要一次性获取，可以使用懒加载加远程搜索 ）
    getAllClientList() {
      if (!this.isLazy) {
        return false
      }
      let params = {
        ...this.queryParams,//分页信息
      }
      this.$api.AllClientList(params).then(response => {
        if (response.code == 200) {
          if (response.data.data && response.data.data.length == 0) {
            this.isLazy = false
          }
          this.clientList = [...this.clientList, ...response.data.data];
        }
      }).catch(error => {
        this.clientList = []
        this.$message.error(error.message)
      })
    },
    //获取所有部门列表
    getAllDepartmentList() {
      this.$api.AllDepartmentList(params).then(res => {
        if (res.code == 200) {
          this.departmentList = res.data
        }
      }).catch(error => {
        this.$message.error(error.message)
      })
    },
    //关闭弹窗
    handleClose() {
      this.$refs.reportForm.resetFields()
      this.form = {}
      this.showDialog = false
    },
    //切换是否完成状态
    changeStatus(val) {
      this.form.status = val
    },
    //获取专利号且填入报告名称
    getPatentNo() {
      if (!this.form.name) {
        var a = this.dictMessage.REPORT_TYPE.filter(item => { return item.dictChildValue == this.form.type })[0].dictChildLabel
        this.$set(this.form, 'name', this.form.signPatentNo + a)
      }
    },
    //修改需要复制的选项
    changeCopyIds(val) {
      if (Object.keys(this.copyIndex).length > 0) {
        var index = this.copyList.findIndex(item => {
          return item.dictChildLabel == '对比文件'
        })
        if (index != -1) {
          var id = this.copyList[index].dictChildValue
          var index2 = this.copyList.findIndex(item => {
            return item.dictChildLabel == '标引信息'
          })
          if (val.indexOf(id) != -1) {
            if (index2 == -1) {
              this.copyList.splice(index + 1, 0, this.copyIndex)
            }
          } else {
            if (index2 != -1) {
              this.copyList.splice(index2, 1)
              this.form.copyIds.splice(this.form.copyIds.indexOf(this.copyIndex.dictChildValue), 1)
            }
          }
        } else {

        }
      }
    },
    // 合并已上传的文件和未上传的文件
    handleConcat(arr) {
      let files = (arr || []).concat(this.files)
      return files
    },
    //切换上传的文件
    onChange(file, fileList) {
      if (this.files && this.files.length > 0) {
        let a = this.files.findIndex(item => {
          return item.size == file.size
        })
        if (a != -1) {
          this.$message.error(`${file.raw.name}文件重复`)
          this.files.splice(a, 1, file.raw)
        } else {
          this.files.push(file.raw)
        }
      } else {
        this.files.push(file.raw)
      }
    },
    //删除未提交的附件
    onRemove(file, fileList) {
      if (file.guid) {
        let a = this.formData[0].systemFileList.findIndex(item => {
          return item.guid == file.guid
        })
        this.formData[0].systemFileList.splice(a, 1)
      } else {
        let a = this.files.findIndex(item => {
          return item.size == file.size
        })
        this.files.splice(a, 1)
      }
    },
    //上传附件时点击查看附件内容
    onPreview(file) {
      var item = {
        name: file.name,
        suffix: '',
        downLoad: true
      }
      var index = file.raw.type.lastIndexOf('/')
      var type = file.raw.type.substring(index + 1, file.raw.type.length)
      var arr = ['png', 'jpeg', 'bmp', 'jpg']
      if (arr.includes(type)) {
        var FileUrl = URL.createObjectURL(file.raw)
        var isPicture = 1
      } else if (type == 'pdf') {
        var FileUrl = URL.createObjectURL(file.raw)
        var isPicture = 0
      } else {
        return false
      }
      const router = this.$router.resolve({
        path: '/checkFile',
        query: {
          row: JSON.stringify(item),
          FileUrl: FileUrl,
          isPicture: isPicture
        }
      })
      window.open(router.href, '_blank');
    },
    //创建无效应对报告下一步
    ifNext() { },
    //提交填写的信息
    submit() {
      this.$refs.reportForm.validate(valid => {
        if (valid) {
          let formData = new FormData()
          if (this.files && this.files.length > 0) {
            for (var i = 0; i < this.files.length; i++) {
              formData.append("files", this.files[i]);
            }
          }
          formData.append('report',this.form)
          if (!this.form.id) {//新增报告
            this.$api.AddReport(formData).then(response => {
              if (response.code == 200) {
                this.files = []
                this.$message.success('报告创建成功')
                this.$emit('getList', true)
                this.handleClose()
              }
            })

          } else {//编辑报告

          }
        }
      })
    },
  },
};
</script>
<style lang="scss" scoped></style>