<template>
  <div>
    <el-dialog
      :title="title"
      :visible.sync="dialogVisible"
      width="500px"
      :before-close="handleClose"
      :append-to-body="true" 
      :close-on-click-modal="false"
    >
      <div>
        <el-form ref="form" :model="form" :rules="rules" >
          <template v-if="firstShow">
            <div>
              <el-form-item label="导入到:" prop="importToType">
                <el-select v-model="form.importToType" clearable @change="changeImportToType" placeholder="请选择">
                    <el-option
                      v-for="(item,key) in importToTypes"
                      :key="item"
                      :label="item"
                      :value="key"
                    >
                    </el-option>
                  </el-select>
              </el-form-item>
              <el-form-item v-if="form.importToType || form.importToType == 0 " :label="'选择' + (importToTypes[form.importToType]?importToTypes[form.importToType]:'')" prop="importToId">
                <div >
                  <el-select v-model.number="form.importToId" filterable remote clearable @change="changeProjectId" placeholder="请选择" v-SelectLazyLoading="lazyLoading" :remote-method="remoteMethod">
                    <el-option
                      v-for="item in ods.data"
                      :key="item.id"
                      :label="item.name"
                      :value="parseInt(item.id)"
                    >
                    </el-option>
                  </el-select>
                <!-- <el-button @click="addProject"><i class="el-icon-plus"></i></el-button> -->
                </div>
              </el-form-item>
            </div>
          </template>
          
          <!-- <el-form-item label="作为对比文件">
                  <el-switch
                    v-model="form.asCompare"
                    active-value="1"
                    active-text="是"
                    inactive-text="否">
                  </el-switch>
                </el-form-item> -->
          <el-form-item label="选择需要关联的标引与分类" v-if="form.importToId && form.importToType!=2">
            <div style="margin-top: 50px">
              <span>栏位：</span>
              <span>
                <el-select
                  v-model="customFieldId"
                  @change="changeCustomField"
                  placeholder="请选择"
                  clearable
                >
                  <el-option
                    v-for="item in customField"
                    :key="item.name"
                    :label="item.name"
                    :value="item.keyValue"
                  >
                  </el-option>
                </el-select>
              </span>
            </div>
            <div style="margin-top: 20px" v-if="customFieldId">
              <template v-if="choseField.type === 0 || choseField.type === 2">
                <el-input
                  v-model="choseField.fieldValue"
                  placeholder="请输入内容"
                  size="small"
                  @change="changeValue"
                ></el-input>
              </template>
              <template v-if="choseField.type === 1">
                <el-date-picker
                  v-model="choseField.fieldValue"
                  value-format="yyyy-MM-dd"
                  type="date"
                  size="small"
                  placeholder="选择日期"
                  style="width: 100%"
                  @change="changeValue"
                ></el-date-picker>
              </template>
              <template v-if="choseField.type === 4">
                <el-radio-group v-model="choseField.fieldValue">
                  <el-radio
                    v-for="option in choseField.options"
                    :key="option.name"
                    :label="option.id"
                    @change="changeValue(option.id, option)"
                    >{{ option.name }}</el-radio
                  >
                </el-radio-group>
              </template>
              <template v-if="choseField.type === 5">
                <el-checkbox-group v-model="choseField.fieldValue">
                  <el-checkbox
                    v-for="option in choseField.options"
                    :key="option.name"
                    :label="option.id"
                    @change="changeValue(option.id, option)"
                    >{{ option.name }}</el-checkbox
                  >
                </el-checkbox-group>
              </template>
              <template v-if="choseField.type === 6">
                <el-tree
                  :ref="choseField.id"
                  :data="choseField.options"
                  node-key="id"
                  :props="treeProp"
                  :expand-on-click-node="false"
                  :default-expand-all="true"
                >
                  <span class="custom-tree-node" slot-scope="{ node, data }">
                    <el-checkbox-group v-model="choseField.fieldValue">
                      <el-checkbox
                        :label="data.id"
                        @change="changeValue(data.id, data)"
                        >{{ data.name }}</el-checkbox
                      >
                    </el-checkbox-group>
                  </span>
                </el-tree>
              </template>
            </div>
            <div v-if="assoImportTaskFieldVOS.length > 0">
              <el-tag
                v-for="(item, index) in assoImportTaskFieldVOS"
                :key="item.fieldValueId"
                >{{ item.fieldName }} = {{ item.fieldValueStr }}
                <span
                  ><i @click="del(index, item)" class="el-icon-error"></i></span
              ></el-tag>
            </div>
          </el-form-item>


          <el-form-item label="下载内容">
            <el-select
              v-model="importContent"
              multiple
              collapse-tags
            >
              <el-option
                v-for="item in importContents"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              >
              </el-option>
            </el-select>
          </el-form-item>
          
          <el-form-item label="是否更新" prop="ifUpdate" v-if="(!form.isUpdateCriteria || (form.isUpdateCriteria && !update.ifUpdate))&&(!form.patentNos || form.patentNos.length==0)">
            <el-switch
              v-model="form.ifUpdate"
              :active-value="true"
              :inactive-value="false"
              active-color="#13ce66"
            >
            </el-switch>
          </el-form-item>
          <template v-if="form.ifUpdate == true && !update.ifUpdate">
            <div>
              <el-form-item label="更新间隔" prop="updateCycle">
                <el-select
                  v-model="form.updateCycle "
                  @change="getDateType"
                  clearable
                  placeholder="请选择更新时间间隔"
                  style="margin-right: 20px"
                >
                  <el-option
                    v-for="item in $constants.updateCycle"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <!-- <el-form-item label="选择更新具体时间" v-if="form.dateType">
                <myTimeChoose
                  :type="form.dateType"
                  @value="handleData"
                  :cron="form.crons"
                  style="width: 300px"
                ></myTimeChoose>
              </el-form-item> -->
            </div>
          </template>
          <el-form-item label="立即导入" prop="importNow" v-if="form.isUpdateCriteria && (!form.patentNos || form.patentNos.length==0)">
            <el-switch
              v-model="form.importNow"
              :active-value="true"
              :inactive-value="false"
              active-color="#13ce66"
            >
            </el-switch>
          </el-form-item>
        </el-form>
        <div class="button">
          <template v-if="form.isUpdateCriteria">
            <el-button
              v-if="form.importToType == 0"
              type="primary"
              size="small"
              @click="onSubmit(2)"
              :loading="btnLoading2"
              >保存定期更新条件</el-button
            >
          </template>
          <template v-else>
            <el-button
              v-if="form.importToType == 0"
              type="primary"
              size="small"
              @click="onSubmit(2)"
              :loading="btnLoading2"
              >仅保存为定期更新条件</el-button
            >
            <el-button
              type="primary"
              size="small"
              @click="onSubmit(1)"
              :loading="btnLoading"
              >导入</el-button
            >
          </template>
          <el-button size="small" @click="handleClose">取消</el-button>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import mixins from "../../mixins";
export default {
  components: {},
  mixins: [mixins],
  props: [],
  data() {
    return {
      title: "",
      btnLoading: false,
      btnLoading2:false,
      dialogVisible: false,
      importToTypes:{
          0: "专题库",
          1: "报告",
          2: "产品",
          // 3: '查新检索报告'
        },
      ods:{
          data:[],
          queryParams:{
            current:1,
            size:10
          },
          loading:false,
      },
      rules:{
        importToId: [
          {required: true, message: '请选择', trigger: 'change'},
        ],
        importToType: [
          {required: true, message: '请选择', trigger: 'change'},
        ],
      },
      firstShow:true,
      update:{}
    };
  },
  watch: {},
  computed: {},
  created() {},
  mounted() {
  },
  methods: {
    async open(form) {
      this.form = {
        ...form,
      };
      if(this.form.importToId){
        this.$set(this.form,'importToId',parseInt(this.form.importToId))
      }
      if (this.form.importToType || this.form.importToType == 0) {
        this.$set(this.form,'importToType',this.form.importToType+'')
        if(this.form.importToType == 3){
          this.title = `导入到查新检索报告`;
        }else{
          this.title = `导入到${this.importToTypes[this.form.importToType]}`;
        }
        this.firstShow = false
        this.rules = {}
      } else {
          this.title = `导入专利`
          this.firstShow = true
          this.rules={
            importToId: [
              {required: true, message: '请选择', trigger: 'change'},
            ],
            importToType: [
              {required: true, message: '请选择', trigger: 'change'},
            ],
          }
      };
      if (this.form.importToId && this.form.importToType == 0) {
        await this.getUpdateCycle()
      }
      if(this.form.isUpdateCriteria){
        this.title = '保存定期更新条件'
        this.$set(this.form,'ifUpdate',true)
      }
      
      this.dialogVisible = true;
    },
    async getUpdateCycle(){
        var params = {
            projectId:this.form.importToId
        }
        await this.$api.queryProjectQuartz(params).then(res=>{
            if(res.code == 200){
                this.update = res.data
            }
        })
    },
    changeImportToType(val){
      this.ods = {
        name:'',
        data:[],
        queryParams:{
          current:1,
          size:10
        },
        loading:false,
      }
      this.$set(this.form,'importToId','')
      this.getData(val)
    },
    getData(val){
      var val1 = Number(val)
      switch(val1){
        case 0:
          this.getProject()
          break;
        case 1:
          this.getReport()
          break;
        case 2:
          this.getProduct()
          break;
      }
    },
    //获取专题库数据
    async getProject(){
      var obj = this.ods
      obj.loading = true;
      let params = {
        ...obj.queryParams,//分页信息
        searchQuery:obj.name?`name=${obj.name}`:'',//检索条件
        orderDTOList: [
          {
            orderBy: "createTime",
            orderType: 1
          },
        ]//排序
      }
      await this.$api.queryPatentProject(params).then(response => {
        if(response.code == 200){
          obj.loading = false;
          obj.data.push(...response.data.data)
          obj.queryParams.total = response.data.total
        }
      })
    },
    //获取报告
    async getReport(){
      var obj = this.ods
      obj.loading = true;
      let params = {
        ...obj.queryParams,//分页信息
        searchQuery:obj.name?`name=${obj.name}`:'',//检索条件
        orderDTOList: [
          {
            orderBy: "createTime",
            orderType: 1
          },
        ]//排序
      }
      await this.$api.queryReportProject(params).then(response => {
        if(response.code == 200){
          obj.loading = false;
          obj.data.push(...response.data.data)
          obj.queryParams.total = response.data.total
        }
      })
    },
    //获取产品
    async getProduct(){
      var obj = this.ods
      obj.loading = true;
      let params = {
        ...obj.queryParams,//分页信息
        searchQuery:obj.name?`product_name=${obj.name}`:'',//检索条件
        orderDTOList: [
          {
            orderBy: "createTime",
            orderType: 1
          },
        ]//排序
      }
      await this.$api.queryProduct(params).then(response => {
        if(response.code == 200){
          obj.loading = false;
          obj.data.push(...response.data.data)
          obj.queryParams.total = response.data.total
        }
      })
    },

     //懒加载事件
     lazyLoading(){
      var obj = this.ods
      if(obj.queryParams.current * obj.queryParams.size>=obj.queryParams.total){
        return false
      }
      obj.queryParams.current += 1
      this.getData(this.form.importToType)
    },
    //远程搜索
    remoteMethod(query){
      var obj = this.ods
      obj.data=[]
      obj.queryParams.current = 1
      obj.name = query
      this.getData(this.form.importToType)
    },

    //打开新增专题库弹窗
    addProject() {
      this.$refs.projectFormDrawer.open(
        {
          ifUpdate: false,
          updateTime: 'day',
          crons: '',
          status: 0,
          sort: 1,
          matterIds: [],
          scenarioIds: [],
        },
        "新增专利数据库"
      );
    },

    //关闭弹窗
    handleClose() {
      this.$refs.form.resetFields();
      this.dialogVisible = false;
    },
    //导入
    onSubmit(type) {
      this.$refs.form.validate((valid) => {
        if (valid) {
          var importContent = []
            this.importContents.forEach(item => {
                var index = this.importContent.indexOf(item.value)
                if(index != -1){
                    importContent.push(1)
                }else{
                    importContent.push(0)
                }
            });
            this.form.importContent = Number(importContent.join(''))
            // this.form.fieldDTOS = this.assoImportTaskFieldVOS
            this.form.fieldDTOS = []
            for(var i = 0;i<this.assoImportTaskFieldVOS.length;i++){
                var choose = this.assoImportTaskFieldVOS[i]
                var index = this.form.fieldDTOS.findIndex(item=>{
                    return item.fieldId == choose.fieldId
                })
                if(index == -1){
                    this.form.fieldDTOS.push(
                        {
                            projectId:choose.projectId,
                            fieldType:choose.fieldType,
                            fieldId:choose.fieldId,
                            fieldValue:[choose.fieldValueId],
                            optionType:2
                        }
                    )
                }else{
                    this.form.fieldDTOS[index].fieldValue.push(choose.fieldValueId)
                }
            }
            // console.log(this.form)
            if(type == 1){
               this.addImportTask(this.form)
            }
            else if(type == 2){
              this.addUpdateCriteria(this.form)
            }
           
        }
      });
    },
    //保存定期更新条件
    addUpdateCriteria(form){
      if(form.importNow){
        this.addImportTask(this.form)
        return
      }
      var conditionImport = this.$s.getSession('conditionImport')
      var params = {
        importToId:form.importToId,
        updateCycle:form.updateCycle,
        importContent:form.importContent,
        ifUpdate:form.ifUpdate,
        searchCondition:form.searchCondition,
        searchSetting:conditionImport?JSON.stringify(conditionImport):'',
        DBType:form.DBType,
        fieldDTOS:form.fieldDTOS
      }
      this.btnLoading2 = true
      this.$api.addQuartzCondition(params).then(response=>{
        if(response.code == 200){
          this.$message.success('定期更新条件保存成功')
          this.btnLoading2 = false
          if(form.isUpdateCriteria){
            this.handleClose()
          }
        }
      }).catch(error=>{
        this.$message.error('定期更新条件保存失败')
        this.btnLoading2 = false
      })
    },
    
    
    //切换项目
     changeProjectId(val) {
      if(!val){
        this.remoteMethod(val)
        return
      }
      if (this.form.importToId && this.form.importToType == 0) {
        this.getUpdateCycle()
      }
      if(this.form.importToId && this.form.importToType != 2){
        this.customFieldId = ''
            //获取所有栏位
            this.getAllCustomField()
      }else{
        var obj = this.ods.data.find(item=>{
          return item.id == val
        })
        this.choseField = {
            id:obj.id,
            name:obj.name,
            type:6,
            isProduct:2,
            fieldValue:[]
          }
        this.customFieldId = val
        this.getProductTree()
      }
    },

    //打开自定义栏位弹窗
    handleManage(reportId) {
      this.$refs.projectFieldDrawer.open(reportId);
    },




  },
};
</script>
<style lang="scss">
@import "@/assets/css/selectButton.scss";
</style>
<style lang="scss" scoped>
.MessageBoxClass {
  color: red;
}
.MessageBoxClass:hover {
  cursor: pointer;
  border-bottom: 1px solid red;
}
.button {
  display: flex;
  justify-content: center;
}
</style>