<template>
  <div>
    <el-dialog title="导入到专题库" :visible.sync="dialogVisible" width="500px" :before-close="handleClose">
        <div>
            <el-form ref="form" :model="form" :rules="rules" label-width="100px">
              <!-- <el-form-item label="任务名称">
                <div>
                  <el-input v-model="form.taskName" placeholder="请输入任务名称"></el-input>
                </div>
              </el-form-item> -->
                <el-form-item label="选择专题库" prop="projectId">
                    <div class="selectButton">
                        <el-select v-model="form.projectId" filterable remote clearable @change="changeProjectId" placeholder="请选择专题库" :loading="loading" v-SelectLazyLoading="lazyLoading" :remote-method="remoteMethod">
                            <el-option
                            v-for="item in projectList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                            >
                            </el-option>
                        </el-select>
                        <el-button @click="addProject"><i class="el-icon-plus"></i></el-button>
                    </div>
                </el-form-item>
                <template v-if="form.projectId" >
                    <div style="margin:10px 0;">
                        <p>选择需要关联的标引与分类</p>
                        <!-- <el-form-item label="选择需要关联的标引与分类"> -->
                            <el-table :data="tableData" :show-header="false">
                                <el-table-column type="expand">
                                    <template slot-scope="props">
                                        <el-form label-position="top" class="custom-field-form">
                                            <template v-if="props.row.field === 'folder'">
                                                <el-tree
                                                    ref="folderTree"
                                                    :data="customField.folder"
                                                    check-strictly
                                                    :default-checked-keys="form.json.field.folder"
                                                    show-checkbox
                                                    node-key="id"
                                                    :props="defaultProps"
                                                    @check-change="changeFolder"
                                                ></el-tree>
                                            </template>
                                            <template v-else v-for="(item, index) in customField[props.row.field]">
                                                <el-form-item :label="`${index + 1}. ${item.name}`">
                                                    <template v-if="item.type === 0 || item.type === 2">
                                                    <el-input v-model="form.json.field[item.id].value" placeholder="请输入内容" size="small"></el-input>
                                                    </template>
                                                    <template v-if="item.type === 1">
                                                    <el-date-picker v-model="form.json.field[item.id].value" value-format="yyyy-MM-dd" type="date" size="small" placeholder="选择日期" style="width: 100%;"></el-date-picker>
                                                    </template>
                                                    <template v-if="item.type === 3">
                                                    <el-select v-model="form.json.field[item.id].value" size="small" placeholder="请选择" class="width_100">
                                                        <el-option v-for="option in item.option" :value="option.id" :label="option.name"></el-option>
                                                    </el-select>
                                                    </template>
                                                    <template v-if="item.type === 4">
                                                    <el-radio-group v-model="form.json.field[item.id].value">
                                                        <el-radio v-for="option in item.option" :label="option.id">{{ option.name }}</el-radio>
                                                    </el-radio-group>
                                                    </template>
                                                    <template v-if="item.type === 5">
                                                    <el-checkbox-group v-model="form.json.field[item.id].value">
                                                        <el-checkbox v-for="option in item.option" :label="option.id">{{ option.name }}</el-checkbox>
                                                    </el-checkbox-group>
                                                    </template>
                                                    <template v-if="item.type === 6">
                                                    <el-tree
                                                        :ref="item.id"
                                                        :data="item.option"
                                                        check-strictly
                                                        :default-checked-keys="form.json.field[item.id].value"
                                                        show-checkbox
                                                        node-key="id"
                                                        :props="defaultProps"
                                                        @check-change="changeField(item.id)"
                                                    ></el-tree>
                                                    </template>
                                                </el-form-item>
                                            </template>
                                        </el-form>
                                    </template>
                                </el-table-column>
                                <el-table-column prop="name" show-overflow-tooltip>
                                    <template slot-scope="scope">
                                        <div style="display:flex;justify-content: space-between;align-items:center">
                                            <span>{{ scope.row.name }}</span>
                                            <span v-if="scope.row.field === 'folder'"><el-button type="primary" size="small" @click="handleFolder(form.projectId)" :disabled="!($permission('/workspace/common/folder_manage') && $r(form.projectId,[1,2]))">文件夹管理</el-button></span>
                                            <span v-else><el-button type="primary" size="small" @click="handleManage(form.projectId)" :disabled="!($permission('/workspace/common/customField') && $r(form.projectId,[1,2]))">自定义栏位管理</el-button></span>
                                        </div>
                                    </template>
                                </el-table-column>
                            </el-table>
                        <!-- </el-form-item>  -->
                    </div>
                </template>
                <el-form-item label="下载内容">
                    <el-select v-model="form.configCells" multiple collapse-tags style="width:100%">
                        <el-option v-for="item in patentField"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="定期更新" prop="taskType">
                    <el-switch v-model="form.taskType" :active-value="1" :inactive-value="0" active-color="#13ce66" inactive-color="#ff4949" @change="changeTaskType"></el-switch>
                </el-form-item>
                <template>
                    <div v-show="form.taskType">
                    <el-form-item label="更新间隔" prop="dateType">
                        <el-select v-model="form.dateType" @change="getDateType" clearable placeholder="请选择更新时间间隔"  style="width:100%">
                        <el-option v-for="item in options"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                        </el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="具体更新时间" v-if="form.dateType"  style="width:100%">
                        <timeChoose loading:type="form.dateType" @value="handleData" :cron="form.crons"></timeChoose>
                    </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>
   

    <project-form-drawer @submit="submitProjectForm" :common-data="commonData" ref="projectFormDrawer"/>

    <project-field-drawer @close="handleClose2" ref="projectFieldDrawer" />

    <project-folder-dialog @close="updateFolder" ref="projectFolderDialog" />
  </div>
</template>

<script>
import ProjectFormDrawer from "@/views/workspace/components/drawer/Form.vue";
import timeChoose from "@/views/workspace/components/common/timeChoose.vue";

import ProjectFieldDrawer from "@/views/workspace/components/drawer/Field";
import ProjectFolderDialog from "@/views/workspace/components/dialog/Folder";
export default {
  components: {
    ProjectFormDrawer,
    timeChoose,
    ProjectFieldDrawer,
    ProjectFolderDialog
  },
  props: [],
  data() {
    return {
      queryParams: {
        current: 1,
        size: 10,
        myself: true,
        name: "",
        sort: {
          order: "desc",
          prop: "create_time",
        },
      },
      isLazy:true,
      loading:false,
      btnLoading:false,
      customField:{},
      tableData:[
        {
            name: '标引',
            field: 'index'
        }, 
        {
            name: '分类',
            field: 'classify'
        }, 
        {
            name: '文件夹',
            field: 'folder'
        }
      ],
      defaultProps: {
        children: 'children',
        label: 'name'
      },
      dialogVisible:false,
      form: {},
      projectList: [],
      commonData:{},
      options: [
        {label:'每天',value:'day'},
        {label:'每周',value:'week'},
        {label:'每月',value:'month'},
        {label:'每年',value:'year'},
      ],
    //   /1.著录项目 2.权要 3.说明书文本 4.说明书pdf 6.摘要附图
      patentField:[
        {
            value:'1',
            label:'著录项目'
        },
        {
            value:'2',
            label:'权利要求'
        },
        {
            value:'3',
            label:'说明书文本'
        },
        {
            value:'4',
            label:'说明书pdf'
        },
        {
            value:'6',
            label:'摘要附图'
        },
      ],
      rules: {
          projectId: [
            { required: true, message: '请选择专题库', trigger: 'change' }
          ],
      }
    };
  },
  watch: {},
  computed: {},
  created() {},
  mounted() {
    this.$api.getCommonData({ keys: 'QUERY_GROUP,ENTERPRISE_APPLICATION_SCENARIO,INVESTIGATION_TYPE' }).then(response => {
      this.commonData = response.data
    })
    this.getProjectList();
  },
  methods: {
    open(form){
        this.form = { 
            ...form,
            configCells:['1','2','3','4','6'],
            taskType2:4,
            taskType:0,
            configId:2,
            json: {
                projectId: 0,
                field: [],
                folder: {}
            }
        }
       if(this.form.projectId){
        this.$set(this.form,'projectId',Number(this.form.projectId))
        var index = this.projectList.findIndex(item=>{
              return item.id == this.form.projectId
            })
            if(index==-1){
              this.$api.getProject({id:this.form.projectId}).then(response=>{
                if(response.code == 200){
                  this.loading = false;
                  this.projectList = [...this.projectList, ...response.data];
                  this.queryParams.projectId = null
                }
              }).catch(error=>{
              })
            }
        
       } 
        this.dialogVisible=true
    },
    //关闭弹窗
    handleClose(){
      this.$refs.form.resetFields()
      this.dialogVisible=false
    },
    //导入
    onSubmit(){
      this.$refs.form.validate((valid) => {
        if (valid) {
          
          this.form.fieldList = []
          this.form.folderIds = this.form.json.field.folder
          for (let id in this.form.json.field) {
              const field = this.form.json.field[id]
              if (!field) {
                  continue;
              }
              const type = field.type
              const value = field.value
              if (value) {
              if (type === 5 || type === 6) {
                  value.map(option => {
                      this.form.fieldList.push({
                      fieldId: parseInt(id),
                      type: type,
                      optionId: option
                  })
                  })
              } else {
                  this.form.fieldList.push({
                  fieldId: parseInt(id),
                  type: type,
                  optionId: [0, 1, 2].indexOf(type) === -1 ? value : 0,
                  text: value
                  })
              }
              }
          }
          this.btnLoading = true
          // this.getConfirm()
          this.$api.addTask(this.form).then(response=>{
              if(response.code == 200){
                this.$message.success(response.data)
                this.btnLoading = false
                this.handleClose()
                this.getConfirm()
            }
          }).catch(error=>{
          })
        }
      })
    },
    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',
      })
      window.open(router.href,'_blank')
    },
    //切换专题库
    changeProjectId(val){
        if(val){
           this.getCustomField(val) 
        }
        
    },
    //获取标引类型
    getCustomField(projectId) {
      this.$api.getCustomField({ projectId: projectId }).then(response => {
        this.customField = response.data;
        ['index', 'classify'].map(key => {
          this.customField[key].map(item => {
            let value = null
            if (item.type === 5 || item.type === 6) {
              value = []
            }
            this.$set(this.form.json.field, item.id, { type: item.type, value })
          })
        })
      })
    },
    //打开自定义栏位弹窗
    handleManage(projectId) {
      this.$refs.projectFieldDrawer.open(projectId)
    },
    //关闭自定义栏位弹窗并更新自定义栏位数据
    handleClose2(projectId) {
      this.getCustomField(projectId)
    },
    //获取选中的分类节点
    changeField(id){
        this.form.json.field[id].value = this.$refs[id][0].getCheckedKeys()
    },
    //打开文件夹管理弹窗
    handleFolder(projectId) {
      this.$refs.projectFolderDialog.open(projectId)
    },
    //关闭文件夹弹窗并更新数据
    updateFolder(projectId) {
      this.$api.getProjectFolderList({ projectId: projectId, patentTotal: false }).then(response => {
        this.customField.folder = response.data
      })
    },
    //获取选中的文件夹
    changeFolder(data, checked, indeterminate){
        this.form.json.field.folder = this.$refs.folderTree.getCheckedKeys()
    },
    //获取更新周期
    getDateType(val) {
      this.form.crons = ''
    },
    //是否定期更新
    changeTaskType(val){
        if(!val){
            this.form.dateType = ''
            this.form.crons = ''
        }
    },
     // 获取时间
     handleData(val) {
      if (this.form.dateType=='') {
        this.$message.error('请先选择更新周期')
        return false
      }
      this.form.crons=val
    },
    // 下拉框懒加载
    lazyLoading() {
      if(!this.isLazy){
        return false
      }
      this.queryParams.current++;
      this.getProjectList();
    },
    //远程搜索
    remoteMethod(query) {
      this.isLazy = true
        if (query !== '') {
          this.loading = true;
          this.queryParams = {
            current:1,
            size:10,
            name:query,
            myself: true,
            sort: {
              order: "desc",
              prop: "create_time",
            },
          }
          this.$api.getProjectListV2(this.queryParams).then(response=>{
            if(response.code == 200){
              this.loading = false;
              this.projectList = response.data.records
            }
          }).catch(error=>{
          })
        } else {
          this.queryParams.name = null
          this.projectList = [];
          this.getProjectList()
        }
      },
    //查询专题库列表
    getProjectList() {
      if(!this.isLazy){
        return false
      }
      this.$api.getProjectListV2(this.queryParams).then((response) => {
        if(response.data.records && response.data.records.length == 0){
            this.isLazy = false
          }
          if(this.form.projectId){
            var index = response.data.records.findIndex(item=>{
              return item.id == this.form.projectId
            })
            if(index!=-1){
              response.data.records.splice(index,1)
            }
          }
          this.projectList = [...this.projectList, ...response.data.records];
      });
    },
    //打开新增专题库弹窗
    addProject() {
      this.$refs.projectFormDrawer.open(
        {
          update: 0,
          updateTime: "一天",
          status: "0",
          sort: 1,
          typeList: [],
          scenarioList: [],
        },
        "新增专题库"
      );
    },
    //更新列表
    submitProjectForm(type) {
      this.getProjectList()
    },
  },
};
</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>