<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 class="project-form">
        <el-main class="project-form-main">
          <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="110px" label-position="left">
            <el-form-item label="专题库名称" prop="name">
              <el-input v-model="ruleForm.name" placeholder="请输入专题库名称"></el-input>
            </el-form-item>
            <el-form-item label="委托方" prop="clientName" v-if="tenantType == 1">
              <!-- <el-input v-model="ruleForm.clientName" placeholder="请选择委托方" @input="input">
                <el-button slot="append" icon="el-icon-search" @click="handleSelect"></el-button>
              </el-input> -->
              <el-autocomplete
              style="width:100%"
                v-model="ruleForm.clientName"
                :fetch-suggestions="querySearch"
                @input="input"
                placeholder="请输入内容"
                :trigger-on-focus="false"
                @select="handleChange"
              >
              <el-button slot="append" icon="el-icon-search" @click="handleSelect"></el-button>
              </el-autocomplete>
            </el-form-item>
            <el-form-item label="负责部门" prop="departmentId">
              <!-- <el-cascader
												ref="deptIdCascader"
                        style="width:100%"
												v-model="departmentId"
												:options="departmentList"
												:show-all-levels="false"
												:props="{
													checkStrictly: true,
													value: 'id',
													label: 'name',
												}"
												clearable
												@change="handleChange2"
												placeholder="请选择部门"
											>
											</el-cascader> -->
            <treeselect
              v-model="ruleForm.departmentId"
              :options="departmentList"
              :disable-branch-nodes="false"
              :show-count="true"
              placeholder="请选择"
              :normalizer="normalizer"
              @select="changeFunctionId"
          />
            </el-form-item>
            <el-form-item label="负责人" prop="person">
              <el-select style="width:100%" v-model="ruleForm.personnelId" filterable placeholder="请选择">
                <el-option
                  v-for="item in personnelList"
                  :key="item.id"
                  :label="item.name"
                  :value="item.id">
                </el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="应用场景" prop="scenarioList">
              <el-checkbox-group v-model="ruleForm.scenarioList" @change="onChange">
                <el-checkbox v-for="item in commonData.ENTERPRISE_APPLICATION_SCENARIO" :label="parseInt(item.value)">{{ item.label }}</el-checkbox>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="调查类型" prop="typeList" v-if="show==true">
              <el-checkbox-group v-model="ruleForm.typeList">
               <template v-for="(item, index) in dictAssociateData">
                  <el-checkbox :label="parseInt(item.dictChildValue)">
                    {{ item.dictChildLabel }}
                  </el-checkbox>
                  <div v-if="index === dictAssociateData.length - 1" class="more-data-box">
                    <el-link v-if="moreData" type="primary" icon="el-icon-arrow-down" @click="handleMoreData(0)">更多
                    </el-link>
                    <el-link v-else type="primary" icon="el-icon-arrow-up" @click="handleMoreData(1)">收起</el-link>
                  </div>
                </template>
                <div v-show="isShow">
                  <el-checkbox v-for="item in dictSecondAssociateData" :label="parseInt(item.dictChildValue)">
                    {{ item.dictChildLabel }}
                  </el-checkbox>
                </div>
              </el-checkbox-group>
            </el-form-item>
            <el-form-item label="技术主题" prop="technicalTheme">
              <el-input v-model="ruleForm.technicalTheme" placeholder="请输入技术主题"></el-input>
            </el-form-item>
            <el-form-item label="相关产品" prop="productId" v-if="$permission('/workspace/product')">
              <div class="selectButton">
                <el-select v-model="ruleForm.productId" filterable clearable placeholder="请选择相关产品" @change="changeProduct">
                  <el-option
                    v-for="item in productList"
                    :key="item.productName"
                    :label="item.productName"
                    :value="item.id">
                  </el-option>
                </el-select>
                <el-button @click="addProduct" v-if="$permission('/workspace/product')"><i class="el-icon-plus"></i></el-button>
              </div>
            </el-form-item>
            <el-form-item label="产品架构" prop="structureId" v-if="showStructure && $permission('/workspace/product')">
              <!-- <el-cascader
                style="width:100%"
                :options="structureList"
                :props="{ checkStrictly: true,label:'structureName',value:'id' }"
                clearable>
              </el-cascader> -->
              <Select-Tree style="width:100%" :options="structureList" @getValue="getStructureId" :props="StructureProp" :value="ruleForm.structureId"></Select-Tree>
            </el-form-item>
            <el-form-item label="是否分类" prop="isCategory" v-if="showStructure && $permission('/workspace/product')">
              <el-switch
                v-model="ruleForm.isCategory"
                active-color="#13ce66"
                inactive-color="#ff4949"
                :active-value="1"
                :inactive-value="0"
                @change="changeIsCategory">
              </el-switch>
            </el-form-item>
            <el-row :gutter="24" v-if="!this.ruleForm.id && $permission('/workspace/event')">
              <el-col :span="24">
                   <el-form-item label="事件">
                    <span slot="label">
                      事件 
                      <el-tooltip class="item" effect="dark" content="事件：商业目标/解决问题/对应项目" placement="top">
                        <i class="el-icon-question"></i>
                      </el-tooltip>
                    </span> 
                      <span v-if="eventAddNewDTOs.length>0">
                        <span v-for="item in eventAddNewDTOs">{{ item.questionName }} &nbsp; </span>
                      </span>
                      <el-button size="small" @click="btnQuestion"> 添加事件 </el-button>
                   </el-form-item>
              </el-col>
            </el-row> 
            
            <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="innerFile">
                  <el-input v-model="ruleForm.innerFile" placeholder="请输入内部案卷"></el-input>
                </el-form-item>
              </el-col>
            </el-row>
            <el-row :gutter="24">
              <el-col :span="12">
                <el-form-item label="委案日" prop="caseDate">
                  <el-date-picker v-model="ruleForm.caseDate" 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="是否更新" required>
                  <el-select v-model="ruleForm.update" 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-col :span="12" v-if="ruleForm.update === 1">
                <el-form-item label="更新周期" required>
                  <el-select v-model="ruleForm.updateTime" placeholder="请选择更新周期" class="width_100">
                    <el-option value="一天" label="一天"></el-option>
                    <el-option value="一周" label="一周"></el-option>
                    <el-option value="一年" label="一年"></el-option>
                  </el-select>
                </el-form-item>
              </el-col>
            </el-row> -->
            <el-form-item label="备注" prop="remark">
              <el-input v-model="ruleForm.remark" placeholder="请输入备注" type="textarea"></el-input>
            </el-form-item>
          </el-form>
        </el-main>
        <el-footer class="footer-common" v-if="($permission('/workspace/project/modify')||$permission('/workspace/project/add')) && ($r(ruleForm.id,[2])||userinfo.id == ruleForm.createBy)">
          <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="500px" append-to-body destroy-on-close :before-close="close2" top="10vh">
      <el-form :inline="true" class="select-user-header-form">
        <el-form-item label="名称">
          <el-input v-model="queryParams.name" size="small" placeholder="请输入名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="" size="small" @click="handleSearch">查询</el-button>
        </el-form-item>
      </el-form>
      <el-table :data="tableData" border header-row-class-name="custom-table-header">
        <el-table-column label="#" type="index" align="center" width="50px"></el-table-column>
        <el-table-column label="名称" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-link type="primary" @click.native="handleChange(scope.row)">{{ scope.row.name }}</el-link>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination :current-page.sync="queryParams.current" :page-size="queryParams.size" :total="total" @current-change="handleCurrentChange" layout="total, prev, pager, next, jumper" background></el-pagination>
      </div>
    </el-dialog>
    <el-dialog title="产品管理" :visible.sync="dialogVisible" width="1300px" append-to-body :close-on-click-modal="false">
      <Product-Manage :clientName="ruleForm.clientName" :sign="sign"  @productId="getProductId"></Product-Manage>
    </el-dialog>
    <el-dialog title="事件" :visible.sync="visibleQuestion" width="1200px" append-to-body :close-on-click-modal="false"
      :before-close="closeQuestion">
      <QuestionAdd  @formData="handleFormData" @resetClose="resetClose" :isCloseFormData="isClose" :eventId="ruleForm.eventId"></QuestionAdd>
    </el-dialog>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
// import ProductManage from '@/views/workspace/product/components/category.vue'
import ProductManage from '@/views/product/components/product.vue'
import SelectTree from '@/views/workspace/folder/articles/components/treeSelect.vue'
import QuestionAdd from '@/views/workspace/folder/questionEvent/components/questionAdd.vue'

export default {
  props: {
    commonData: Object
  },
  components: {
    Treeselect,
    ProductManage,
    SelectTree,
    QuestionAdd,
  },
  data() {
    const isClientId = (rule,value,callback)=>{
      if(this.tenantType == 1){
        if(value){
          callback()
        }else{
          callback(new Error('请选择委托方'))
        }
      }else{
        callback()
      }
    }
    return {
      StructureProp:{
        label:'structureName',
        value:'id',
        children:'children'
      },
      showStructure:false,
      dialogVisible:false,
      visibleQuestion:false,
      inline:true,
      sign:1,
      tenantType:'',
      clientList:[],
       test: {
        value: '1',
        type: 'ENTERPRISE_APPLICATION_SCENARIO',
        flag: 1
      },
				departmentList:[],
        personnelList:[],
        productList:[],//产品数据
        structureList:[],//架构数据
        departmentId:'',
         dictAssociateData: {},
      dictSecondAssociateData: {},
      moreData: true,
      isShow: false,
      departmentId:12,
      show:false,
      loading: false,
      drawer: false,
      visible: false,
      title: '',
      ruleForm: {},
      tableData: [],
      queryParams: {
        name: '',
        size: 10,
        current: 1,
      },
      total: 0,
      rules: {
        name: [{ required: true, message: '请输入专题库名称', trigger: 'blur' },],
        // clientName: [{ required: true, validator:isClientId, trigger: 'blur' },],
        // typeList: [{ required: true, message: '请选择调查类型', trigger: 'change' },],
        // scenarioList: [{ required: true, message: '请选择应用场景', trigger: 'change' },],
        // status: [{ required: true, message: '请选择处理状态', trigger: 'change' },],
        // productId: [{ required: false, validator:isProductId, trigger: 'change' },],
      },
      eventAddNewDTOs:[],//事件集合
      isClose: false,//关闭新增专题库时删除事件
      isArr:[],
    }
  },
  computed: {
    ...mapGetters(['permissions','userinfo'])
  },
watch:{
 	departmentId() {
				if (this.$refs.deptIdCascader) {
					this.$refs.deptIdCascader.dropDownVisible = false;
				}
  },
},
  created() {
    
  },
  mounted() {
    this.tenantType = this.userinfo.tenantType
    this.getDepartment()
    this.getPersonnelList()
    this.getAllClientList()
    this.getProductList()

  },
  methods: {
    //查询产品信息
    async getProductList() { 
     await this.$api.queryProducts({}).then(res => {
        if (res.code==200) {
          this.productList = res.data.list
        }
      })
    },
    //查询架构信息
    async getStructureList(val){
      var params={
        productId:val,
        structureId:0
      }
      await this.$api.queryStructures(params).then(response=>{
        if(response.code == 200){
          this.structureList = response.data.children
        }
      })
    },
    //改变相关产品id
    changeProduct(value){
      if(value){
        if(this.ruleForm.isCategory!= 0 && this.ruleForm.isCategory!=1){
          // this.ruleForm.isCategory = 1
          this.$set(this.ruleForm,'isCategory',1)
        }
        this.ruleForm.structureId = ''
        this.getStructureList(value)
        this.showStructure = true
      }else{
        this.ruleForm.structureId = ''
        this.$set(this.ruleForm,'isCategory',null)
        this.showStructure = false
      }
    },
    //获取架构id
    getStructureId(val){
      this.ruleForm.structureId = val
    },
    //打开添加产品弹窗
    addProduct(){
      this.dialogVisible = true
    },
    //获取产品id
    getProductId(val){
      if(!val){
        this.getProductList()
        return false
      }
      var index = this.productList.findIndex(item=>{
        return item.id == val
      })
      if(index == -1){
        this.getProductList()
      }
      this.ruleForm.productId = val
      this.ruleForm.structureId = ''
      this.getStructureList(val)
      this.showStructure = true
      this.dialogVisible = false
    },
    //改变是否分类的值
    changeIsCategory(val){
      // console.log(val)
    },
    querySearch(queryString, cb) {
        var clientList = this.clientList;
        var results = (queryString ? clientList.filter(this.createFilter(queryString)) : clientList).map(item=>{
          return {
            value:item.name,
            name:item.name,
            id:item.id
          }
        });
        // 调用 callback 返回建议列表的数据
        cb(results);
      },
      createFilter(queryString) {
        return (clientList) => {
          return (clientList.name && clientList.name.toLowerCase().indexOf(queryString.toLowerCase()) != -1);
        };
      },
      getAllClientList(){
        this.$api.getAllClientList({}).then(response=>{
          this.clientList = response.data
        })
      },
    changeFunctionId(val){
      // this.ruleForm.departmentId = val.id
      // console.log(this.departmentId)
    },
     normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      };
    },
    getPersonnelList(){
      this.$api.getPermissionPersonnelList().then((response)=>{
        this.personnelList=response.data
      })
    },
    getDepartment() {
				this.$api.getPermissionDepartmentList().then((response) => {
					this.departmentList = response.data;
				});
			},
    onChange() {
      // console.log(this.ruleForm.scenarioList)
      if(this.ruleForm.scenarioList.length!=0){
        this.show=true

         this.test.value = this.ruleForm.scenarioList.toString()
        this.test.flag = 1
        this.$api.getDictTreeByParentDictValue(this.test).then(response => {
          this.dictAssociateData = response.data

          this.test.value = this.ruleForm.scenarioList.toString()
          this.test.flag = 0
          this.$api.getDictTreeByParentDictValue(this.test).then(response => {
            this.dictSecondAssociateData = response.data
          })
        })
      }else{
        this.show=false
      }

    },
  handleMoreData(type) {
      if (type === 0) {
        this.isShow = true
        this.test.value = this.ruleForm.scenarioList.toString()
        this.test.flag = 0

        this.$api.getDictTreeByParentDictValue(this.test).then(response => {
          this.dictSecondAssociateData = response.data
        })
      } else if (type === 1) {
        this.isShow = false
      }
      this.moreData = !this.moreData
    },

    close() {
      this.drawer = false
      this.eventAddNewDTOs=[]
      this.ruleForm.eventAddNewDTOs = []
      this.isClose=!this.isClose
      this.$emit('close')
    },
    close2() {
      this.visible = false
    },
    getClientList() {
      this.$api.getAdminClientList(this.queryParams).then(response => {
        this.tableData = response.data.records
        this.total = response.data.total
      })
    },
    handleSelect() {
      this.visible = true
      this.getClientList()
    },
    input() {
      this.$set(this.ruleForm, 'clientId', -1)
    },
    handleCurrentChange(val) {
      this.queryParams.current = val;
      this.getClientList();
    },
    handleSearch() {
      this.queryParams.current = 1
      this.getClientList()
    },
    handleChange(row) {
      this.$set(this.ruleForm, 'clientId', row.id)
      this.$set(this.ruleForm, 'clientName', row.name)
      this.close2()
    },
     handleChange2() {
      
    },
    async open(row, title) {
      this.ruleForm = { ...row }
      this.$set(this.ruleForm,'scenarioNames',[])
      if(this.ruleForm.productId){
       await this.getStructureList(this.ruleForm.productId)
        this.showStructure = true
      }else{
        this.showStructure = false
      }
      if(this.ruleForm.scenarioList && this.ruleForm.scenarioList.length!=0){
        this.show=true
        this.onChange()
      }else{
        this.ruleForm.scenarioList = []
        this.show=false
      }
      if(this.ruleForm.eventId){
        this.eventAddNewDTOs=[
          {
            id:this.ruleForm.eventId,
            questionName:this.ruleForm.eventName
          }
        ]
        this.ruleForm.eventAddNewDTOs = this.eventAddNewDTOs
      }
      this.title = title
      this.drawer = true
    },
    updateClient({ clientId, clientName }) {
      this.$set(this.ruleForm, 'clientId', clientId)
      this.$set(this.ruleForm, 'clientName', clientName)
    },
    submit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          this.show=false
          this.loading = true
          if (this.ruleForm.id) {
            this.$api.editProject(this.ruleForm).then(response => {
              this.loading = false
              this.$message.success('编辑成功')
              this.$emit('submit', 0)
              this.close()
            }).catch(error => {
              this.loading = false
            })
          } else {
            this.$api.addProject(this.ruleForm).then(response => {
              this.loading = false
              let permissions = this.permissions
              permissions[response.data] = 0
              this.$store.commit('SET_PERMISSIONS', permissions)
              this.$message.success('新增成功')
              this.$emit('submit', 1)
              this.close()
            }).catch(error => {
              this.show=true
              this.loading = false
            })
          }
        }
      })
    },
    // 添加事件按钮
    btnQuestion() {
      this.visibleQuestion=true
    },
    // 事件弹窗关闭
    closeQuestion() {
        this.visibleQuestion=false
    },
    resetClose() {
      this.closeQuestion()
    },
    // 保存或重置事件
    handleFormData({ list, option }) {
      this.eventAddNewDTOs=JSON.parse(JSON.stringify(list))
      this.ruleForm.eventAddNewDTOs = this.eventAddNewDTOs
      if (option == 1 && this.isArr.length === 0) {
        this.closeQuestion()
      }
     
    },
  }
}
</script>
<style>


</style>
<style lang="scss">
@import '@/assets/css/selectButton.scss';

.project-form {
  .project-form-main {
    background: #fff;
    padding: 20px;
  }
}

</style>
