<template>
  <div>
    <el-drawer class="custom-drawer-form" :title="title" size="800px" append-to-body :visible.sync="drawer"
      direction="rtl" :before-close="close" destroy-on-close>
      <el-container>
        <el-main>
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="130px" label-position="left"
            class="demo-ruleForm">
            <el-form-item label="专利数据库名称" prop="name">
              <el-input v-model="ruleForm.name" placeholder="请输入专利数据库名称"></el-input>
            </el-form-item>
            <template>
              <div>
                <el-form-item label="委托方" prop="entrustName" v-if="userinfo.tenantType == 1">

                  <mySelectButton size='large' style="width:100%" @click="handleSelect" >
                    <div style="width:100%">
                      <el-autocomplete style="width:100%" v-model="ruleForm.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="departmentId" v-else>
                  <mySelectTree style="width:100%" v-model="ruleForm.departmentId" :options="departmentList">
                  </mySelectTree>
                </el-form-item>
              </div>
            </template>
            <el-form-item label="负责部门" prop="departmentId">
              <mySelectTree style="width:100%" v-model="ruleForm.departmentId" :options="departmentList"></mySelectTree>
            </el-form-item>
            <el-form-item label="负责人" prop="person">
              <el-select style="width:100%" v-model.number="ruleForm.headId" filterable remote clearable placeholder="请选择"
                :loading="personnelList.loading" v-SelectLazyLoading="loadHead" :remote-method="remoteMethod">
                <el-option v-for="item in personnelList.data" :key="item.id" :label="item.name" :value="parseInt(item.id)">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="事件" prop="event" v-if="!ruleForm.id">
              <mySelectButton size='large' style="width:100%" @click="addEvent" >
                    <div style="width:100%">
                      <el-select style="width:100%" v-model="ruleForm.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>
            <template v-if="(ruleForm.id && !(ruleForm.eventIds && ruleForm.eventIds.length)) || !ruleForm.id">
              <div>
                <el-form-item label="应用场景" prop="scenarioIds">
                  <el-checkbox-group v-model="ruleForm.scenarioIds" @change="onChange" :disabled="Boolean(ruleForm.eventId)">
                    <el-checkbox v-for="item in commonData" :key="item.id"
                      :label="parseInt(item.id)">{{ item.name }}</el-checkbox>
                  </el-checkbox-group>
                </el-form-item>
                <el-form-item label="调查类型" prop="matterIds" v-if="show == true">
                  <el-checkbox-group v-model="ruleForm.matterIds">
                    <template >
                      <el-checkbox v-for="(item, index) in dictAssociateData" :key="index" :label="parseInt(item.id)">
                        {{ item.name }}
                      </el-checkbox>
                    </template>
                  </el-checkbox-group>
                </el-form-item>
              </div>
            </template>
            
            <template>
              <div>
                <el-form-item label="产品类别/产品" prop="productId">
                  <div>
                    <div v-if="ruleForm.products">
                      {{ ruleForm.products.name }}
                      <span style="color:blue">
                        ({{ ruleForm.products.treeType==2?'产品':'产品类别' }})
                      </span>
                      <span><i class="el-icon-error cursor_pointer" @click="delProduct"></i></span>
                    </div>
                    <el-button size="small" v-else @click="choseProduct">+ 选择</el-button>
                  </div>
                </el-form-item>
                <el-form-item label="分类架构" prop="structureId" v-if="ruleForm.products && ruleForm.products.fieldId">
                  <my-select-Tree style="width:100%" :options="structureList" :props="StructureProp" v-model="ruleForm.structureId"></my-select-Tree>
                </el-form-item>
              </div>
            </template>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="合同号" prop="contractNo">
                  <el-input v-model="ruleForm.contractNo" placeholder="请输入合同号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="内部案卷" prop="volumeNumber">
                  <el-input v-model="ruleForm.volumeNumber" placeholder="请输入内部案卷"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="委案日" prop="commissionCaseDay">
                  <el-date-picker v-model="ruleForm.commissionCaseDay" value-format="yyyy-MM-dd" type="date" placeholder="请选择委案日"
                    class="width_100"></el-date-picker>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item label="处理状态" prop="status">
                  <el-select v-model="ruleForm.status" placeholder="请输入处理状态" class="width_100">
                    <el-option value="0" label="处理中"></el-option>
                    <el-option value="1" label="已完成"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="是否更新" prop="ifUpdate">
                  <el-select v-model="ruleForm.ifUpdate" placeholder="请选择是否更新" class="width_100">
                    <el-option :value="false" label="否"></el-option>
                    <el-option :value="true" label="是"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12" v-if="ruleForm.ifUpdate">
                <el-form-item label="更新周期" required>
                  <el-select v-model="ruleForm.updateTime" @change="getDateType" placeholder="请选择更新周期" class="width_100">
                    <el-option v-for="item in $constants.updateCycle" :key="item.value" :value="item.value" :label="item.label"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="24">
                <el-form-item label="更新具体时间" v-if="ruleForm.ifUpdate && ruleForm.updateTime" >
                  <my-Time-Choose :type="ruleForm.updateTime" @value="getValue" :cron="ruleForm.crons" style="width:300px"></my-Time-Choose>
                </el-form-item>
              </el-col>
            </el-row>
            <el-form-item label="附件" prop="systemFileList">
              <myUpload :file-list="ruleForm.systemFileList" @on-change="onchangeFile" @on-remove="onRemove" style="height: 180px;" :autoUpload="true"></myUpload>
            </el-form-item>
            <el-form-item label="备注" prop="description">
              <el-input v-model="ruleForm.description" placeholder="请输入备注" type="textarea"></el-input>
            </el-form-item>
          </el-form>
        </el-main>
        <el-footer class="footer-common">
          <el-button @click="close">取 消</el-button>
          <el-button type="primary" @click="submit" :loading="loading">确 定</el-button>
        </el-footer>
      </el-container>
    </el-drawer>

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

    <el-dialog title="选择产品或产品类别" :visible.sync="productVisible" width="1000px" :append-to-body="true" :close-on-click-modal="false" destroy-on-close :before-close="closeProduct">
      <div style="height:550px">
        <product :isChoose="true" @chooseItem="chooseItem"></product>
      </div>
    </el-dialog>

    <addEvent ref="addEvent"  @isSuccess="handleSuccess"></addEvent>
  </div>
</template>

<script>
import ClientTable from '@/views/client'
import { mapGetters } from 'vuex';

import product from '@/views/product/components/index.vue'
import addEvent from '@/views/event/components/dialog/addEvent.vue'; 
import { cron } from "@/utils/model/time/mixins";
export default {
  components: {
    ClientTable,
    product,
    addEvent
  },
  mixins:[cron],
  props: {
    commonData: Array
  },
  data() {
    return {
      //抽屉标题
      title: '',
      //抽屉开关标识
      drawer: false,
      //表单数据
      ruleForm: {},
      //表单规则
      rules: {},
      //控制选择委托方弹窗
      visible: false,
      //部门列表
      departmentList: [],
      //人员列表
      personnelList: {
        queryParams:{
          current:1,
          size:10
        },
        data:[]
      },
      //确认按钮
      loading: false,
      //显示调查类型
      show: false,


      //调查类型列表
      dictAssociateData: [],

      //用来获取调查类型
      test: {
        value: '1',
        type: 'ENTERPRISE_APPLICATION_SCENARIO',
        flag: 1
      },
      //事件列表
      eventList:{
        queryParams:{
          current:1,
          size:10
        },
        data:[]
      },
      //选择产品或产品类别
      productVisible:false,
      //产品或产品类别架构
      structureList:[],
      StructureProp:{
        value:'id',
        label: 'name',
        children: 'child'
      },
      //委托方
      clientList:{
        queryParams:{
          current:1,
          size:10
        },
        data:[],
        cb:null
      },
      

    };
  },
  watch: {},
  computed: {
    ...mapGetters(['userinfo'])
  },
  created() { },
  mounted() {
  },
  methods: {
    //切换更新周期
    getDateType(val){
      this.ruleForm.crons = ''
    },
    getValue(val){
      if (this.ruleForm.dateType=='') {
        this.$message.error('请先选择更新周期')
        return false
      }
      this.ruleForm.crons=val
    },

    //获取架构id
    getStructureId(val){

    },

    //获取选中的值
    chooseItem({row,type}){
      this.ruleForm.products = {
              treeType:type,
              fieldId:row.id,
              name:row.name,
              valueIds:[]
      }
      this.closeProduct()
      this.getFramework()
    },
    //获取产品架构集合
    getFramework(){
      let params = {
        type: this.ruleForm.products.treeType,//类型：1产品类别，2产品，3技术分类，4自定义树
        typeId: this.ruleForm.products.fieldId,//产品或类别id
      }
      this.$api.queryTreeNodeTree(params).then(res => {
        if (res.code == 200) {
          this.structureList = res.data.data
        }
      }).catch(err => {
      })
    },
    //删除选择的产品或产品类别
    delProduct(){
      this.ruleForm.products = null
      this.$forceUpdate()
      // this.ruleForm.products=null
    },
    //打开选择产品或产品类别弹窗
    choseProduct(){
      this.productVisible = true
    },
    //关闭弹窗
    closeProduct(){
      this.productVisible = false
    },


    //打开弹窗
    async open(form, title) {
      this.ruleForm = JSON.parse(JSON.stringify(form))
      //获取部门列表
      this.getDepartment()
      
      if(this.ruleForm.scenarioIds && this.ruleForm.scenarioIds.length!=0){
        this.show=true
        this.onChange()
      }else{
        this.ruleForm.scenarioIds = []
        this.show=false
      }

      if(!this.ruleForm.id){
        this.eventList.data = []
        this.eventList.name = ''
        this.eventList.disabled = false
        if(this.ruleForm.eventId){
          this.eventList.disabled = true
          this.eventList.data.push({
            id:this.ruleForm.eventId,
            name:this.ruleForm.eventName,
          })
        }else{
          this.getEventList()
        }
        
      }

      this.personnelList.data = []
      this.personnelList.queryParams.name = ''
      console.log(this.ruleForm)
      if(this.ruleForm.headId){
        this.personnelList.queryParams.id = this.ruleForm.headId
        await this.getPersonnelList(1)
        this.personnelList.queryParams.id = null
      }
      //获取人员列表
      this.getPersonnelList()

      if(this.ruleForm.crons){
        this.ruleForm.updateTime = this.getType(this.ruleForm.crons)
      }

      this.title = title
      this.drawer = true
    },
    //关闭抽屉
    close() {
      this.drawer = false
      this.clientList.queryParams.name = ''
      this.personnelList.queryParams.name = ''
    },

    //获取部门列表
    getDepartment() {
      this.$api.getPermissionDepartmentList().then((response) => {
        this.departmentList = response.data;
      });
    },

    /**
     * 事件
     */
    //打开事件弹窗
    addEvent(){
      this.$refs.addEvent.open(null, 1)
    },
    //事件新增成功
    handleSuccess(){
      this.eventList.data=[]
      this.eventList.queryParams.current = 1
      this.eventList.name = ''
      this.getEventList()
    },
    //切换事件
    changeEvent(val){
      if(!val){
        this.ruleForm.scenarioIds = []
        this.show = false
        this.ruleForm.matterIds = []
        return 
      }
      var obj = this.eventList.data.find(item=>{
        return item.id == val
      })
      if(obj){
        this.ruleForm.scenarioIds = [obj.scenarioId]
        this.show = true
        this.onChange()
      }
    },
    //懒加载事件
    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(){
      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;
          this.eventList.data.push(...response.data.data)
          this.eventList.queryParams.total = response.data.total
        }
      })
    },

    //获取人员列表(懒加载)
    loadHead(){
      if(this.personnelList.queryParams.current * this.personnelList.queryParams.size>=this.personnelList.queryParams.total){
        return false
      }
      this.personnelList.queryParams.current += 1
      this.getPersonnelList()
    },
    async getPersonnelList(type) {
      this.personnelList.loading = true;
      await this.$api.getPermissionPersonnel(this.personnelList.queryParams).then((response) => {
        if(response.code == 200){
          this.personnelList.loading = false;
          if(!type){
            var index = response.data.findIndex(item=>{
                return item.id == this.ruleForm.headId
              })
              if(index!=-1){
                response.data.splice(index,1)
              }
              this.personnelList.queryParams.total=response.pageColumn.total
          }
          this.personnelList.data.push(...response.data)
        }
      })
    },
    //人员远程搜索
    remoteMethod(query) {
          this.personnelList.data=[]
          this.personnelList.queryParams.current = 1
          this.personnelList.queryParams.name = query
          this.getPersonnelList()
    },

    
    //远程搜索委托方（建议调取接口获取）
   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.ruleForm, 'entrustId', -1)
    },
    //切换选择委托方
    handleChange(row) {
      this.$set(this.ruleForm, 'entrustId', row.id)
      this.$set(this.ruleForm, 'entrustName', row.name)
      this.close2()
    },
    //打开选择委托方弹窗
    handleSelect() {
      this.visible = true
    },
    //获取委托方信息
    getClient(row) {
      this.$set(this.ruleForm, 'entrustId', row.id)
      this.$set(this.ruleForm, 'entrustName', row.name)
      this.close2()
    },
    //关闭委托方弹窗
    close2() {
      this.visible = false
    },

    //调查类型选择切换
    onChange() {
      if (this.ruleForm.scenarioIds.length != 0) {
        this.show = true
        this.$api.getMatter(this.ruleForm.scenarioIds).then(response => {
          this.dictAssociateData = response.data.data
        })
      } else {
        this.show = false
      }
    },
    // 上传的文件监听
    onchangeFile(file, fileList) {
      if(!this.ruleForm.systemFileList){
        this.$set(this.ruleForm,'systemFileList',[])
      }
      if (file.guid) {
        let index = this.ruleForm.systemFileList.findIndex(item => {
          return item.uid == file.uid
        })
        if (index != -1) {
          this.ruleForm.systemFileList.splice(index, 1, file)
        }
      } else {
        this.ruleForm.systemFileList.push(file.raw)
      }
    },
    // 删除上传的文件
    onRemove(file, fileList) {
      let index = this.ruleForm.systemFileList.findIndex(item => {
        return item.uid == file.uid
      })
      if (index != -1) {
        this.ruleForm.systemFileList.splice(index, 1)
      }
    },
    //提交数据
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.show = false
          this.loading = true
          this.ruleForm.trees = []
          if(this.ruleForm.products){
            this.ruleForm.trees.push(this.ruleForm.products)
          }
          var scenarioIds = JSON.parse(JSON.stringify(this.ruleForm.scenarioIds))
          if(this.ruleForm.eventId){
            this.ruleForm.events = []
            this.ruleForm.scenarioIds = []
            this.ruleForm.matterIds.forEach(item=>{
              this.ruleForm.events.push(
                {
                  matterId:item,
                  scenarioId:scenarioIds[0],
                  eventId:this.ruleForm.eventId
                }
              )
            })
          }
         // 判断文件是否都上传完毕
         var guids = this.$commonJS.checkUploadFile(this.ruleForm.systemFile)
            if(!guids){
                return false
            }
            this.ruleForm.fileGuids = guids
          if (this.ruleForm.id) {
            this.$api.updatePatentProject(this.ruleForm).then(response => {
              this.loading = false
              this.$message.success('编辑成功')
              this.$emit('submit', 0)
              this.close()
            }).catch(error => {
              this.loading = false
            })
          } else {
            this.$api.addPatentProject(this.ruleForm).then(response => {
              this.loading = false
              this.$message.success('新增成功')
              this.$emit('submit', 1)
              this.close()
            }).catch(error => {
              this.ruleForm.scenarioIds = JSON.parse(JSON.stringify(scenarioIds))
              this.show = true
              this.loading = false
            })
          }
        }
      })
    },
  },
};
</script>
<style lang="scss" scoped></style>