<template>
  <div class="g-main" >
    <div v-show="pageType == 'list'">
      <div class="m-table" :style="{ height: tableHeight }">
        <div class="flex f-endpoint" v-if="showTitle">
          <div class="flex" >
            <div style="align-items: center;justify-items: center;" class="f-align_item flex"
            :class="selectedIndex === index ? 'f-align_item' : 'f-align_item_active'" v-for="(item, index) in titleList" :key="item.value"
              @click="selectItem(index)">
              <span>{{ item.label }}</span>
            </div>
          </div>
          <div class="flex  " style="align-items: center;">  
            <el-button @click="handeleUpdate" v-if="selectedIndex==1"  size="small" type="primary">上传共享数据
                    </el-button>
            <el-button v-if="selectedIndex==2" type="primary" style="" size="small"
              @click="onClick('add')">新建图片集</el-button>
            <el-input @blur="onSelect" v-model="name" :placeholder="searchBox" class="oval-input"
              prefix-icon="el-icon-search" style="width: 200px; margin-left: 20px;"></el-input>
          </div>
        </div>
        <el-table v-if="selectedIndex==0" :data="tableData" border class="m-table-item" style="width: 100%"
          :height="maxTableHeight">
          <el-table-column prop="excelName" align="center" label="文件名称" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <div class="flex">
                <img style=" width: 25px; height: 25px; left: 10px;"
                :src="require(`@/assets/images/index/Excel.png`)" alt="">
              <span  style="margin-left: 10px">{{ scope.row.excelName
                }}</span>
              </div>
        
            </template>
          </el-table-column>
          <el-table-column prop="taskTitle" label="所属任务"  align="center" :show-overflow-tooltip="true" />
          <el-table-column prop="taskPeriod" align="center"  label="任务周期" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              {{ scope.row.taskPeriod === 'once' ? '一次性' : scope.row.taskPeriod === 'weekly' ? '每周' :
              scope.row.taskPeriod
              === 'halfMonth'?'每半月': scope.row.taskPeriod === 'month'?'每月':'每季度'}}
            </template>
          </el-table-column>
          <el-table-column prop="taskStateName" align="center"  label="状态" :show-overflow-tooltip="true">
            <template slot-scope="scope">
              <span
                :class="scope.row.taskStateName==='未提交'?'yellow':scope.row.taskStateName==='已提交'?'blue':scope.row.taskStateName=='(已驳回)未提交'?'red':'green'">{{
                scope.row.taskStateName
                }}</span>
            </template>
          </el-table-column>
          <el-table-column prop="redDot" label="下载人数" align="center" :show-overflow-tooltip="true" >
            <template slot-scope="scope">
              <el-button type="text" @click="onClickRecord(scope.row)">{{ scope.row.redDot}}</el-button>
            </template>
          </el-table-column>
          <el-table-column prop="agencyName" align="center" label="所属组织" :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column prop="createByName" align="center"  label="创建人" :show-overflow-tooltip="true">
          </el-table-column>
          <el-table-column prop="createdTime" align="center" width="140" :show-overflow-tooltip="true" label="创建时间">
          </el-table-column>
          <el-table-column fixed="right" label="操作" align="center" width="200px">
            <template slot-scope="scope">
              <el-button @click=" handleInfo(scope.row)" type="text" size="small">查看</el-button>
            </template>
          </el-table-column>

        </el-table>
        <div v-if="selectedIndex==0">
          <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
            :current-page.sync="pageNo" :page-sizes="[20, 50, 100, 200]" :page-size="parseInt(pageSize)"
            layout="sizes, prev, pager, next, total" :total="total">
          </el-pagination>
        </div>
        <div>
          <data-sharing ref="dataSharing":name="name"v-if="selectedIndex==1" @pictureClose="pictureClose" @pictureOpen="pictureOpen"></data-sharing>
        </div>
        <div>
          <picture-collection  :name="name" @pictureOpen="pictureOpen" @pictureClose="pictureClose"  ref="picture_collection" v-if="selectedIndex==2"></picture-collection>
        </div>

      </div>
    </div>
    <el-dialog :visible.sync="formShow" :close-on-click-modal="false" :close-on-press-escape="false" :title="pictureTitle"
      width="950px" top="15vh" class="dialog-h" @closed="closeAdd">
      <picture-add  v-if="formShow" ref="ref_form" @closeAdd="closeAdd"></picture-add>
    </el-dialog>
    <el-dialog :visible.sync="showUpdate" :close-on-click-modal="false" :close-on-press-escape="false" title="上传共享数据"
      width="950px" top="15vh" class="dialog-h" @closed="closeUpdataAdd">
      <upload-data-add  v-if="showUpdate" ref="ref_form" @closeUpdataAdd="closeUpdataAdd"></upload-data-add>
    </el-dialog>
    <div v-if="showdownloadRecord">
      <el-dialog title="下载记录" :visible.sync="showdownloadRecord" width="50%" :close-on-click-modal="false">
        <export-shared v-if="showdownloadRecord" :showType="showdownloadRecord" :taskId="downloadRecord.taskId"></export-shared>
      </el-dialog>
    </div>
    <div v-if="pageType == 'info'">
      <share-excel v-if="pageType == 'info'"  @handleShowPage="handleShowPage"  :infoObj="infoObj" :workbookId=task></share-excel>
    </div>
  </div>
</template>
  <script>
  import { requestPost, requestGet } from "@/js/dai/request";
  import nextTick from "dai-js/tools/nextTick";
  import { mapGetters } from "vuex";
  import shareExcel from "./cpts/share-excel";
  import excelAdd from "./cpts/excel-add";
  import exportShared from "./cpts/export-shared.vue"
  import dataSharing from "./cpts/data-sharing.vue"
  import pictureCollection from "./cpts/picture-collection.vue"
  import * as echarts from "echarts";
  import pictureAdd  from './cpts/picture-add.vue'
  import uploadDataAdd from "./cpts/upload-data-add.vue"
  export default {
    components: { exportShared,dataSharing,pictureCollection,shareExcel,pictureAdd,uploadDataAdd},
  
    data() {
    
      let endDisabledDate = (time) => {
        //这个关键属性我们一定要写在data的里面并且return的外面，这是动态改变区间的关键
        let nowData = Date.now();
        if (this.formData.startTime) {
          let startTime = new Date(this.formData.startTime);
          return (
            time.getTime() > nowData ||
            time.getTime() < startTime ||
            time.getTime() === startTime
          );
        } else {
          return time.getTime() > nowData;
        }
      };
      let startDisabledDate = (time) => {
        //这个关键属性我们一定要写在data的里面并且return的外面，这是动态改变区间的关键
        let nowData = Date.now();
        return time.getTime() > nowData;
      };
      return {
        pictureTitle:"新增图片",
        showUpdate:false,
        downloadRecord:{

        },
        infoObj:{},
        searchBox:"按文件名称关键字搜素",
        showTitle:true,
        name:"",
        formShow:false,
        showdownloadRecord:false,
        selectedIndex: 0, // 记录选中的项
        titleList:[
          {
            value:0,
            label:'任务文件'
          },
          {
            value:1,
            label:'共享数据'
          },
          {
            value:2,
            label:'共享图片集'
          },
        ],
        task: "",
        pageType: "list", // 列表list 新增add 详情info
        tableData: [],
        formData: {
          orgId: '',//组织Id
          taskTitle: '',//任务主题
          taskState: '',//任务类型
          startTime: '',//开始时间
          endTime: '',//结束时间
          createdBy: ''//创建人
        },
        pageNo: 1,
        pageSize: window.localStorage.getItem("pageSize") || 20,
        total: 1,
        sarr: [],
        endPickerOptions: {
          disabledDate: endDisabledDate,
        },
        startPickerOptions: {
          disabledDate: startDisabledDate,
        },
        searchH: 180,
        createdByArray: [],
        statusArray: [
          {
            label: '已完成',
            value: 'resolved'
          },
          {
            label: '已取消',
            value: 'cancel',
          },
          {
            label: '进行中',
            value: 'deal',
          }
        ],
        manager: false
      };
    },
    computed: {
      tableHeight() {
        return (this.clientHeight - 140) + 'px'
    },
    ...mapGetters(['clientHeight', 'resolution']),
      maxTableHeight() {
              const h = this.clientHeight - this.searchH - 100+ this.iframeHeight;
              const _h = this.clientHeight - 100- this.searchH;
              return this.$store.state.inIframe ? h : _h;
          },
          ...mapGetters(["clientHeight", "iframeHeight"]),
    },
    watch: {
    },
    async mounted() {
      const user = this.$store.state.user;
      this.getTableData()
    },
    methods: {
      closeUpdataAdd(){
        this.showUpdate=false
        this.$refs.dataSharing.getTableData()
      },
      handeleUpdate(){ 
        console.log("东方军事对抗疗法");
        this.showUpdate=true
      },
      async uploadHttpRequest(file) {
            this.importLoading = true;
            this.importBtnTitle = '正在上传中...';
            this.$message({
                showClose: true,
                dangerouslyUseHTMLString: true,
                message: "导入中，请到系统管理-<a id='clickA' style='cursor: pointer;'>导入记录</a>中查看进度",
                duration: 3000
            });
            let than = this;
            document.getElementById('clickA').addEventListener('click', function () {
                than.$router.replace('/main/importRecord-index');
            });
            const formData = new FormData(); //FormData对象，添加参数只能通过append('key', value)的形式添加
            formData.append('file', file.file); //添加文件对象
            formData.append('code', ''); //添加文件对象
            let url = '/governance/icEvent/importEvent'
            if (this.importType == 2) {
              url = '/governance/icEvent/importAwo'
            }
            console.log(url)
            await this.$http
                .post(url, formData)
                .then(res => {
                    if (res.data.code == 0 && res.data.msg == 'success') {
                        const data = res.data.data;
                        this.dataList = [
                            ...Object.keys(data.option.exist).map(k => {
                                return {
                                    index: k,
                                    srcField: data.option.exist[k],
                                    exist: true,
                                    field: data.option.exist[k]
                                };
                            }),
                            ...Object.keys(data.option.notExist).map(k => {
                                return {
                                    index: k,
                                    srcField: data.option.notExist[k],
                                    exist: false,
                                    field: ''
                                };
                            })
                        ];
                        this.importOption = data.option;
                        this.importCode = data.code;
                        this.fileData = file;
                    } else this.$message.error(res.data.msg);
                })
                .catch(err => {
                    console.log('失败', err);
                    file.onError(); //上传失败的文件会从文件列表中删除
                });
            this.importLoading = false;
            this.importBtnTitle = '导入';
            this.$refs.upload.clearFiles();
            this.getTableData();
        },
      handleExcelSuccess(res, file) {
            if (!res.code === 0 && !res.msg === 'success') {
                this.$message.error(res.msg);
            }
        },
      handleProgress(event, file, fileList) {

      },
      beforeExcelUpload(file) {
            const isType = file.type === 'application/vnd.ms-excel';
            const isTypeComputer = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet';
            const fileType = isType || isTypeComputer;
            const isLt1M = file.size / 1024 / 1024 < 10;
            if (!fileType) {
                this.$message.error('上传文件只能是xls/xlsx格式！');
            }

            if (!isLt1M) {
                this.$message.error('上传文件大小不能超过 10MB!');
            }
            return fileType && isLt1M;
        },
      pictureOpen(){
        console.log("pictureOpen");
        this.showTitle=true
      },
      pictureClose(){
        console.log("dfklsdfkl");
        
        this.showTitle=false
      },
      onSelect() {
        if (this.selectedIndex == 2) {
          this.$nextTick(() => {
            console.log("dsfjsdklf");
            this.$refs.picture_collection.getTableData();
          });
        } else if (this.selectedIndex===0) {
          this.formData.taskTitle=this.name
          this.getTableData()
        }
        else if (this.selectedIndex===1) {
          console.log(this.name,"sdfkl;sd");
          // this.formData.taskTitle=this.name
          this.$nextTick(() => {
            console.log("dsfjsdklf");
            this.$refs.dataSharing.formData.name=this.name;
            this.$refs.dataSharing.getTableData();
          });
  
        }
      

      },
      closeAdd(){
        this.formShow=false
        this.$nextTick(() => {  
            console.log("dsfjsdklf");
             this.$refs.picture_collection.getTableData();
      });
    },
      onClick(type,id){
        this.formShow=true
      
        this.$nextTick(() => {
             this.$refs.ref_form.initForm(type,id);
      });
    },  
      onClickRecord(row){
        console.log(row,"fsd;lkds;lf");
        this.downloadRecord=row
        this.showdownloadRecord=true
      },
      selectItem(index) {
        this.selectedIndex = index; // 选中点击的项
        // this.name="按文件名称关键字搜索";
        // if(index===0){
        //   this.searchBox="按文件名称关键字搜索"
        //   this.getTableData()
        // }
        // else if (index===1) {
        //   this.searchBox="按文件名称关键字搜索"
        // }else{
        //   this.searchBox = "按图片名称关键字搜索"
        // }

      },
      async handleCancel(item) {
        let parms = {
          id: item.id,
        };
        this.$confirm("取消之后无法恢复，确认取消？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            requestPost('/actual/base/communityOneTablePublish/cancelTask', parms).then(res => {
              if (res.code == 0) {
                this.pageNo = 1
                this.getTableData()
              }
            })
          })
          .catch((err) => {
            if (err == "cancel") {
            }
          });
      },
      async getStafflist() {
        let parms = {
          orgId: this.$store.state.user.agencyId,
          orgType: 'agency',
          pageNo: 1,
          pageSize: 100,
        };
        let { data, code } = await requestPost('/data/aggregator/org/stafflist', parms)
        if (code === 0) {
          this.createdByArray = data.staffList;
        }
      },
      handleShowPage() {
        this.pageType = 'list';
        this.getTableData()
      },
      handleAdd() {
        this.pageType = 'add';
        console.log(this.pageType);
      },
      handleInfo(item) {
        console.log(item,"sdlkjsdfkl");
        const { id, taskId, taskTitle, taskPeriod,createByName, taskType, taskIntroduction,subWorkBookId,workBookId,taskStateName} = item;
        this.infoObj = { id, taskId, taskTitle, taskPeriod, taskType, taskIntroduction,createByName};
        console.log(item, "dkljsfdlk");
        this.task = item.workBookId
        this.pageType = 'info'
      },
      getLastItem(list, vals, key) {
        let LIST = list || [];
        for (let item of LIST) {
          // console.log(item[key]);
          for (let i of vals) {
            if (item[key] === i) {
              this.sarr.push(item);
            } else {
              this.getLastItem(item.subAgencyList, vals, key);
            }
          }
        }
      },
      handleSizeChange(val) {
        this.pageSize = val;
        window.localStorage.setItem("pageSize", val);
        this.getTableData();
      },
      handleCurrentChange(val) {
        this.pageNo = val;
        this.getTableData();
      },
      async getTableData() {
        const url = "/actual/base/communityOneTablePeriodPublish/sharePage";
        const { pageSize, pageNo, formData } = this;
        const { data, code, msg } = await requestGet(url, {
          pageSize,
          pageNo,
          ...formData
        });
        if (code === 0) {
          this.total = data.total || 0;
          this.tableData = data.list
            ? data.list.map((item) => {
              return item;
            })
            : [];
        } else {
          this.$message.error(msg);
        }
      },
      handleSearch() {
        this.pageNo = 1;
        this.getTableData();
      },
     async handleDel(item){
      let parms = {
          id: item.id,
        };
        this.$confirm("删除之后无法恢复，确认删除？", "提示", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            requestPost('/actual/base/communityOneTablePublish/delete', parms).then(res => {
              if (res.code == 0) {
                this.getTableData()
              }
            })
          })
          .catch((err) => {
            if (err == "cancel") {
            }
          });
      },
     async resetSearch() {
        this.$refs.ref_searchform.resetFields();
        this.pageNo = 1;
        const user = this.$store.state.user;
        if (user) {
          if (user.roleList.findIndex(item => item === "manager") !== -1) {
            this.manager = false;
          } else {
            this.manager = true;
            this.formData.createdBy = this.createdByArray.find(item => item.mobile === user.phone).staffId
          }
        }
        this.getTableData();
      },
    },
  };
  </script>
  
  <style lang="scss" scoped>
  @import "@/assets/scss/modules/management/list-main.scss";

  .m-search {
    .u-item-width-normal {
      width: 200px;
    }


  }

  .yellow {
    color: #ddaa5d;
  }

  .blue {
    color: #4e89ec;
  }

  .red {
    color: #fc2b3b;
  }

  .green {
    color: #2fcbbd;
  }

  .f-align_item {
    padding: 10px;
    cursor: pointer;
    font-size: 16px;
    border-bottom: 3px solid blue;
  }
  .f-align_item_active {
    padding: 10px;
    color: blue !important; /* 强制应用颜色 */
    cursor: pointer;
    font-size: 16px;
    border-bottom: 3px solid #ffffff;
  }

  // .f-align_item.active {
  //   font-size: 16px;
  //   color: blue;
  //   border-bottom: 5px solid blue;
  //   /* 点击时的下划线 */
  // }

  .f-align_item span {
    color: black;
    /* 默认文字颜色 */
  }

  .chart-container {
    width: 100%;
    display: flex;
    justify-content: center;
    align-items: center;
  }

  .chart {
    width: 100%;
    height: 350px;
  }
  .oval-input  {

    ::v-deep(.el-input__inner) {
    border-color: #dbdada !important; /* 默认加深边框 */
    border-radius: 25px !important;
}
}
</style>