<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="导入到:">
                <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">
            <div style="margin-top: 50px" v-if="form.importToType!=2">
              <span>栏位：</span>
              <span>
                <el-select
                  v-model="customFieldId"
                  @change="changeCustomField"
                  placeholder="请选择"
                >
                  <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: 40px" 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"
                    @input="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">
            <el-switch
              v-model="form.ifUpdate"
              :active-value="true"
              :inactive-value="false"
              active-color="#13ce66"
              inactive-color="#ff4949"
            >
            </el-switch>
          </el-form-item>
          <template v-if="form.ifUpdate">
            <div>
              <el-form-item label="更新间隔" prop="dateType">
                <el-select
                  v-model="form.dateType"
                  @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>
        <div class="button">
          <el-button
            type="primary"
            size="small"
            @click="onSubmit"
            :loading="btnLoading"
            >导入</el-button
          >
          <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,
      dialogVisible: false,
      importToTypes:{
          0: "专题库",
          1: "报告",
          2: "产品",
        },
      ods:{
          data:[],
          queryParams:{
            current:1,
            size:10
          },
          loading:false,
      },
      rules:{},
      firstShow:true,
    };
  },
  watch: {},
  computed: {},
  created() {},
  mounted() {
  },
  methods: {
    open(form) {
      this.form = {
        ...form,
      };
      if (this.form.importToType) {
        this.title = `导入到${this.importToTypes[this.form.importToType]}`;
        this.firstShow = false
      } else {
          this.title = `导入专利`
          this.firstShow = true
      };
      if (this.form.importToId) {

      }
      this.dialogVisible = true;
    },
    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(
        {
          update: 0,
          updateTime: "一天",
          status: "0",
          sort: 1,
          typeList: [],
          scenarioList: [],
        },
        "新增专题库"
      );
    },

    //关闭弹窗
    handleClose() {
      this.$refs.form.resetFields();
      this.dialogVisible = false;
    },
    //导入
    onSubmit() {
      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.assoImportTaskFieldVOS = this.assoImportTaskFieldVOS
            // console.log(this.form)
            this.addImportTask(this.form)
        }
      });
    },
    //弹窗
    getConfirm() {
      const h = this.$createElement;
      this.$msgbox({
        title: "提示",
        message: h("p", null, [
          h("span", null, "任务正在导入，查看任务进度请前往 "),
          h(
            "span",
            {
              class: "MessageBoxClass",
              on: {
                click: () => {
                  this.toTaskList();
                  // 通过close关闭消息弹窗，this.$confirm就是this.$confirm.close(false)，其他同理
                  this.$msgbox.close(false);
                },
              },
            },
            "任务清单"
          ),
        ]),
        type: "warning",
        showConfirmButton: false,
      }).then((action) => {});
    },
    //跳转到任务清单
    toTaskList() {
      // 传专题库id是查到当前专题库的导入任务，不传是查看所有导入任务
      const router = this.$router.resolve({
        path: "/taskList",
        query:{
          importToId:this.form.importToId
        }
      });
      window.open(router.href, "_blank");
    },
    //切换项目
    changeProjectId(val) {
      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>