<template>
  <div class="workspace">
    <el-card shadow="never" class="workspace-card nopadding">
      <div class="query-top">
        <el-collapse>
          <el-collapse-item title="图表预览" name="1">
            <div class="chart-box">
              <total-chart ref="totalChart" />
            </div>
          </el-collapse-item>
        </el-collapse>
      </div>
      <!-- <div class="query-list workspace-query">
        <div class="title">
          <p>条件分组:</p>
        </div>
        <div class="content">
          <el-checkbox-group :disabled="!$permission('/workspace/project/check')" v-model="queryParams.group" @change="onChange">
            <el-checkbox v-for="item in commonData.QUERY_GROUP" :label="parseInt(item.value)">{{ item.label }}</el-checkbox>
          </el-checkbox-group>
        </div>
      </div> -->
      <!-- <div class="query-list workspace-query">
        <div class="title">
          <p>应用场景:</p>
        </div>
        <div class="content">
          <el-checkbox-group :disabled="!$permission('/workspace/project/check')" v-model="queryParams.scenario" @change="onChange">
            <el-checkbox v-for="item in commonData.ENTERPRISE_APPLICATION_SCENARIO" :label="parseInt(item.value)">{{ item.label }} <b v-if="queryTotal.scenario" class="label">({{ queryTotal.scenario[item.label] }})</b></el-checkbox>
          </el-checkbox-group>
        </div>
      </div>
      <div class="query-list workspace-query">
        <div class="title">
          <p>调查类型:</p>
        </div>
        <div class="content">
          <el-checkbox-group :disabled="!$permission('/workspace/project/check')" v-model="queryParams.type" @change="onChange" class="type">
            <template v-for="(item, index) in commonData.INVESTIGATION_TYPE">
              <el-checkbox v-if="!moreData || [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13].indexOf(parseInt(item.value)) !== -1" :label="parseInt(item.value)">{{ item.label }} <b v-if="queryTotal.type" class="label">({{ queryTotal.type[item.label] }})</b></el-checkbox>
              <div v-if="index === commonData.INVESTIGATION_TYPE.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>
          </el-checkbox-group>
        </div>
      </div> -->
      <!-- <div class="query-list">
        <div class="title">
          <p>条件查询:</p>
        </div>
        <div class="content" style="display:flex;justify-content: flex-start;">
          <el-select v-model="querySelect" size="small" placeholder="请选择" class="workspace-search-select">
            <el-option value="0" label="项目名称"></el-option>
            <el-option value="4" label="内部案卷"></el-option>
            <el-option value="1" label="委托方"></el-option>
            <el-option value="2" label="技术主题"></el-option>
            <el-option value="3" label="负责部门"></el-option>
          </el-select>
          <div style="width:230px;height:32px;margin-left:10px" v-if="querySelect==3">
          <treeselect
              v-model="department.querySearch2"
              :options="departmentList"
              :disable-branch-nodes="false"
              :show-count="true"
              placeholder="请选择"
              :normalizer="normalizer"
              @select="changeFunctionId"
          /></div>
        <el-input v-else v-model="querySearch" placeholder="请输入查询内容" size="small" class="workspace-search-input"></el-input>
          <el-button size="small" type="primary" class="margin-left_10" icon="el-icon-search" @click="handleSearch" :disabled="!$permission('/workspace/project/check')">搜索</el-button>
        </div>
      </div> -->

      <el-container>
        <el-header>
            <div>
              <mySearch style="width:500px" :SearchFields="searchFiled" @search="search" :searchValue="searchOption" :disabled="!$permission('/workspace/project/check')"></mySearch>  
            </div>
            <div style="display:flex;margin-right:10px">
                <div>
                    <span>分组查询：</span>
                    <el-select v-model="queryParams.group" :disabled="!$permission('/workspace/project/check')" multiple clearable collapse-tags size="small" @change="onChange" style="width:200px">
                        <el-option v-for="item in commonData.QUERY_GROUP" :key="item.value" :label="item.label" :value="parseInt(item.value)">
                        </el-option>
                    </el-select>
                </div>
                <el-button-group class="margin-left_10">
                  <el-button :type="queryShowType === '0' ? 'primary' : ''" @click="onChange2('0')" size="small">列表</el-button>
                  <el-button :type="queryShowType === '1' ? 'primary' : ''" @click="onChange2('1')" size="small">卡片</el-button>
                </el-button-group>
                <el-dropdown trigger="click" split-button type="primary" size="small">
                    <p @click="handleAdd" v-disabled="!$permission('/workspace/project/add')">新增专题库</p>
                    <el-dropdown-menu slot="dropdown" class="text-align_center">
                        <el-dropdown-item @click.native="handleExport">导出列表</el-dropdown-item>
                        <el-dropdown-item @click.native="handleImport" :disabled="!$permission('/workspace/project/import')">导入数据包</el-dropdown-item>
                        <el-dropdown-item @click.native="handleField">显示栏位管理</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>
            </div>
        </el-header>
        <el-main class="workspace-main" v-loading="loading">
          <component :is="viewType" :data="dataList"  @checkVisual="checkVisual" :common-data="commonData" :group="queryParams.group" :params="queryParams" :field="projectField" @option="handleOption" @sort="handleSort"></component>
          <div style="text-align: center;">
            <el-pagination
                backgroundx
                layout="total, prev, pager, next, jumper"
                :current-page.sync="queryParams.current"
                :page-size.sync="queryParams.size"
                @current-change="handleCurrentChange"
                :total="total">
            </el-pagination>
          </div>
        </el-main>
      </el-container>
<!-- 
      <div class="query-bottom">
        <div class="left">
          <el-button size="small" type="primary" @click="handleAdd" v-if="$permission('/workspace/project/add')">新增专题库</el-button>
          <el-button size="small" type="warning" @click="handleExport" :loading="btnLoading">导出列表</el-button>
            <el-button type="success" size="small" @click.native="handleImport" :disabled="!$permission('/workspace/project/import')">
              导入数据包
            </el-button>
        </div>
        <div class="right">
          <el-button type="warning" size="small" style="display: inline-block;margin-right: 10px;" @click="handleField">显示栏位管理</el-button>
          <div style="margin-top: 10px;margin-right: 10px;display: inline-block;">
            <el-button-group>
              <el-button :type="queryShowType === '0' ? 'primary' : ''" @click="onChange2('0')" size="small">列表</el-button>
              <el-button :type="queryShowType === '1' ? 'primary' : ''" @click="onChange2('1')" size="small">卡片</el-button>
            </el-button-group>
          </div>  
        </div>
      </div>
      <el-main class="workspace-main" v-loading="loading">
        <component :is="viewType" :data="dataList"  @checkVisual="checkVisual" :common-data="commonData" :group="queryParams.group" :params="queryParams" :field="projectField" @option="handleOption" @sort="handleSort"></component>
        <div style="text-align: center;">
          <el-pagination
              backgroundx
              layout="total, prev, pager, next, jumper"
              :current-page.sync="queryParams.current"
              :page-size.sync="queryParams.size"
              @current-change="handleCurrentChange"
              :total="total">
          </el-pagination>
        </div>
      </el-main> -->
    </el-card>

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

    <project-file-drawer  ref="projectFileDrawer" />

    <project-user-drawer  ref="projectUserDrawer" />

    <project-share-drawer  ref="projectShareDrawer" />

    <project-import-drawer @close="getList" ref="projectImport" />

    <project-table-field @update="updateProjectField" ref="projectTableField" />
    <visualDialog ref="visualDialog"></visualDialog>
  
  </div>
</template>

<script>
import CommonTable from "./components/CommonTable";
import CommonCard from "./components/CommonCard";
import MergeTable from "./components/MergeTable";
import MergeCard from "./components/MergeCard";
import TotalChart from "./components/TotalChart";
import ProjectFormDrawer from './components/drawer/Form'
import ProjectFileDrawer from "./components/drawer/File";
import ProjectUserDrawer from "./components/drawer/User";
import ProjectShareDrawer from "./components/drawer/Share";
import ProjectImportDrawer from './components/drawer/Import'
import ProjectTableField from './components/dialog/TableField'
import { downLoad, getTotalPage, getFileName } from "@/utils";
import { mapGetters } from 'vuex'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

import visualDialog from '@/views/home/components/visualDialog.vue';
import { openVisual } from "@/views/home/components/mixins";

export default {
  components: {
    CommonTable,
    CommonCard,
    MergeTable,
    MergeCard,
    TotalChart,
    ProjectImportDrawer,
    ProjectFormDrawer,
    ProjectFileDrawer,
    ProjectUserDrawer,
    ProjectShareDrawer,
    ProjectTableField,
    Treeselect,
    visualDialog
  },
  mixins:[openVisual],
  data() {
    return {
      searchFiled:[
            {
                label:'项目名称',
                value:'name',
                type:1,
                placeholder:'请输入项目名称'
            },
            // {
            //     label:'委托方',
            //     value:'clientName',
            //     type:1,
            //     placeholder:'请输入委托方'
            // },
            {
                label:'技术主题',
                value:'technicalTheme',
                type:1,
                placeholder:'请输入技术主题'
            },
            {
                label:'负责部门',
                value:'departmentId',
                type:3,
                placeholder:'请选择负责部门'
            },
            {
                label:'内部案卷',
                value:'innerFile',
                type:1,
                placeholder:'请输入内部案卷'
            },
        ],
      searchOption:{
        name: localStorage.searchContent,
      },
      department:{},
      departmentList:[],
      projectField: [],
      queryParams: {
        group: [],
        type: [],
        scenario: [],
        
        technicalTheme: '',
        clientName: '',
        size: 10,
        current: 1,
        sort: {
          order: 'desc',
          prop: 'create_time'
        },
        myself: false,
        innerFile: ''
      },
      moreData: true,
      commonData: {},
      total: 0,
      querySelect: '0',
      querySearch: localStorage.searchContent,
      queryShowType: '0',
      viewType: 'CommonTable',
      loading: false,
      btnLoading: false,
      dataList: [],
      title: '',
      queryTotal: {},
      row: {},
    }
  },
  computed: {
    ...mapGetters(['userinfo'])
  },
  mounted() {
    this.$api.getCommonData({ keys: 'QUERY_GROUP,ENTERPRISE_APPLICATION_SCENARIO,INVESTIGATION_TYPE' }).then(response => {
      this.commonData = response.data
    
    })
    this.getList()
    this.getProjectField()
    this.getDepartment()
    this.getScenarioAndTypeTotal()
  },
  // activated() {
  //   this.getList()
  // },
  methods: {
    //搜索
    search(val){
      var params = {}
      if(val.length>0){
        val.forEach(item => {
          if(item.type == 3){
            params[item.value] = item.searchValue.map(item1=>{
              return item1.value
            }) 
          }else{
            params[item.value] = item.searchValue.label
          }
        });
      }
      this.searchOption = params
      this.queryParams.current = 1
      this.getList()
    },
    changeFunctionId(val){
      // console.log(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
      };
    },
      getDepartment() {
				this.$api.getPermissionDepartmentList().then((response) => {
					this.departmentList = response.data;
          this.searchFiled.find(item=>{
            return item.value == 'departmentId'
          }).options = this.departmentList.map(item=>{
            return {
              value:item.id,
              label:item.name
            }
          })
				});
			},
    getTotalPage,
    handleClose() {

    },
    getScenarioAndTypeTotal() {
      this.$api.getScenarioAndTypeTotal().then(response => {
        this.queryTotal = response.data
        this.$refs.totalChart.initData(response.data)
      })
    },
    handleMoreData(type) {
      this.moreData = !this.moreData
    },
    // importExcel(file, fileList) {
    //   this.btnLoading = true
    //   let formData = new FormData()
    //   formData.append('file', file.raw)
    //   this.$api.importProjectExcel(formData).then(async (response) => {
    //     this.btnLoading = false
    //     const res = await this.$api.getPermissions()
    //     this.$store.commit('SET_PERMISSIONS', res.data)
    //     this.getList()
    //     this.getScenarioAndTypeTotal()
    //   }).catch(error => {
    //     this.btnLoading = false
    //   })
    // },
    getProjectField() {
      let params = {
        projectId: 0,
        type: 'project'
      }
      this.$api.getUserSettingField(params).then(response => {
// console.log( response.data,'获取表格的数据');
        this.projectField = response.data.filter(item=>{
          if(this.userinfo.tenantType != 1){
            return item.name!='委托方'
          }
          return item
        })
      })
    },
    updateProjectField(data) {
      this.projectField = data
    },
    handleField() {
      // console.log(this.projectField)
      this.$refs.projectTableField.open(this.projectField)
    },
    onChange() {
      this.queryParams.current = 1
      this.getList()
      this.handleChangeView()
    },
    onChange2(type) {
      this.queryShowType = type
      this.onChange()
    },
    handleChangeView() {
      let view = [
          ['CommonTable', 'CommonCard'],
          ['MergeTable', 'MergeCard'],
      ]
      if (this.queryParams.group.length === 0) {
        // console.log(view[0][this.queryShowType],'777777');
        this.viewType = view[0][this.queryShowType]
      } else {
        this.viewType = view[1][this.queryShowType]
        // console.log(this.viewType)
      }
    },
    handleSearch() {
      this.queryParams.current = 1
      this.queryParams.name = ''
      this.queryParams.clientName = ''
      this.queryParams.technicalTheme = ''
      this.queryParams.departmentId=''
      switch (this.querySelect) {
        case "0":
          this.queryParams.name = this.querySearch
          break
        case "1":
          this.queryParams.clientName = this.querySearch
          break
        case "2":
          this.queryParams.technicalTheme = this.querySearch
          break
        case "3":
          this.queryParams.departmentId = this.department.querySearch2
          break
        case "4":
          this.queryParams.innerFile = this.querySearch
          break
      }
      this.getList()
    },
    handleImport() {
      this.$refs.projectImport.open()
    },
    handleExport() {
      this.btnLoading = true
      this.$api.exportProjectList().then(response => {
        downLoad(response, getFileName('xlsx'))
        this.btnLoading = false
      }).catch(error => {
        this.btnLoading = false
      })
    },
    handleAdd() {
      this.$refs.projectFormDrawer.open({
        update: 0,
        updateTime: '一天',
        status: '0',
        sort: 1,
        typeList: [],
        scenarioList: []
      }, '新增专题库')
    },
    handleEdit(row) {
      this.$refs.projectFormDrawer.open(row, '专题库信息')
    },
    handleCurrentChange(val) {
      this.queryParams.current = val;
      this.getList();
    },
    getList() {
      if (this.queryParams.group.length) {
        this.queryParams.size = 99999
      } else {
        this.queryParams.size = this.queryShowType === '0' ? 10 : 12
      }
      var params = this.queryParams
        params = {
          ...this.queryParams,
          ...this.searchOption
        }
      this.loading = true
      this.$api.getProjectListV2(params).then(response => {
        // console.log(response.data.records,'8888888');
        this.dataList = response.data.records
        this.total = response.data.total
        this.loading = false
      }).catch(error=>{
        this.dataList = []
        this.total = 0
        this.loading = false
      })
    },
    handleDelete(row) {
      this.$confirm('确认删除本条数据吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        this.loading = true
        this.$api.deleteProject({ id: row.id }).then(response => {
          this.$message.success('删除成功')
          this.loading = false
          this.getList()
          this.getScenarioAndTypeTotal()
        }).catch(error => {
          this.loading = false
        })
      })
    },
    handleSort(sort) {
      this.queryParams.sort = { ...sort }
      this.getList()
    },
    handleOption({ option, row }) {
      this.$store.commit('SET_PROJECT_ID', row.id)
      switch (option) {
        case '0':
          this.handleImportPatent(row)
          break
        case '1'://分配参与者
          this.handleUser(row)
          break
        case '2'://报告管理
          this.handleFile(row, 1)
          break
        case '5'://其它附件
          this.handleFile(row, 0)
          break
        case '3'://项目分享
          this.handleShare(row)
          break
        case '4'://删除
          this.handleDelete(row)
          break
        case '6'://产品分类
          this.frameworkIndex(row)
          break
        case '7'://Excel导入
          this.handleImportPatent(row)
          break;
        case '8'://手动导入
          this.download(row, 8)
          break;
        case '9'://网站导入
          this.download(row, 9)
          break
        case '11'://条件导入即接口导入
          this.importPatent(row)
          break;
        case '12'://跳转到任务清单
          this.toTaskList(row)
          break;
        case '10'://问题（事件）
          this.questionEvent(row)
          break
        case 'e'://编辑
          this.handleEdit(row)
          break
      }
    },
    //条件导入即接口导入
    importPatent(row){
      this.$router.push({
        path: '/conditionImport',
        query: {
          projectId: row.id,
        }
      })
    },
    //跳转到任务清单
    toTaskList(row){
      const router = this.$router.resolve({
        path: '/taskList',
        query: {
          projectId: row.id,
        }
      })
      window.open(router.href,'_blank')
    },
    frameworkIndex(row) {
      const router = this.$router.resolve({
        path: '/frameworkIndex',
      })
      var a = {
        id:row.productId,
        productName:row.productName,
        structureId:row.structureId
      }
      this.$s.setSession('productRow',a)
      window.open(router.href, '_blank');
    },
    handleFile(row, type) {
      this.$refs.projectFileDrawer.open(row.id, type)
    },
    handleShare(row) {
      this.$refs.projectShareDrawer.open(row.id)
    },
    handleUser(row) {
      this.$refs.projectUserDrawer.open(row.id)
    },
    handleImportPatent(row) {
      this.$router.push({
        path: '/import',
        query: {
          projectId: row.id
        }
      })
    },
    download(row,option) {
      this.$router.push({
        path: '/PatentNoImport',
        query: {
          projectId: row.id,
          option:option,
          update:row.update,
        }
      })
    },
    questionEvent(row) {
      this.$router.push({
        path: '/questionEvent',
        query: {
          projectId: row.id,
        }
      })
    },
    submitProjectForm(type) {
      this.getList()
      if (type) {
        this.getScenarioAndTypeTotal()
      }
    },
  }
}
</script>
<style lang="scss" scoped>
  
</style>
<style lang="scss">
 
.content .vue-treeselect__control{
  height: 32px;
  .vue-treeselect__placeholder, .vue-treeselect__single-value{
    top:-5px
  }
}
.workspace {
  .workspace-card {
    min-height: 100%;
    padding-bottom: 15px;
    .workspace-query {
      border-bottom: 1px solid #bbb;
      .content {
        .label {
          
          color: #1e9fff
        }
        .type {
          .el-checkbox {
            height: 30px;
          }
          .more-data-box {
            position: relative;
            display: inline-block;
            margin-left: 25px;
            top: -5px;
          }
        }
      }
    }
    .workspace-search-input {
      width: 230px;
      padding-left: 10px;
    }
    .workspace-search-select {
      width: 110px;
    }
    .workspace-project-pagination {
      display: inline-block;
      b {
        color: #1e9fff
      }
    }
    .workspace-project-order {
      width: 80px;
    }
    .workspace-main {
      padding-top: 10px;
      width: 100%;
    }
  }
  .nopadding .el-card__body {
    padding: 0 !important;
  }
  .query-top {
    border-bottom: 1px solid #bbb;
    padding-bottom: 10px;
    .el-collapse {
      border-bottom: 0 !important;
      border-top: 0 !important;
      .el-collapse-item__wrap, .el-collapse-item__header {
        border-bottom: 0 !important;
      }
      .el-collapse-item__header {
        padding-left: 15px;
        font-weight: bold;
      }
      .is-active .el-collapse-item__wrap {
        border-top: 1px solid #bbb;
      }
    }
    .chart-box {
      height: 250px;
    }
  }
  .query-bottom {
    padding: 0 10px;
    border-top: 1px solid #bbb;
    .left {
      float: left;
      padding: 10px;
    }
    .right {
      float: right;
      .c {
        padding: 10px;
        display: table-cell;
      }
    }
  }
  .query-list {
    display: flex;
    .title {
      background: #ddd;
      width: 130px;
      font-size: 13px;
      font-weight: bold;
      color: #666;
      float: left;
      display: flex;
      align-items: center;
      p {
        margin: 0;
        padding-left: 15px;
      }
    }
    .content {
      width: calc(100% - 130px);
      float: right;
      padding: 15px;
    }
  }
}
</style>
