<template>
  <basic-container>
    <div class="search-box">
        <div class="search-box-left">
            <el-input v-model="query.name" placeholder="请输入名称" style="width: 200px;" class="filter-item"   size="small"/>
            <el-select v-model="query.projectId" placeholder="项目名称" clearable style="width: 200px" class="filter-item"   size="small">
              <el-option v-for="item in projectList" :key="item.id" :label="item.projectAlias" :value="item.id" />
            </el-select>
            <el-select v-model="query.tabType" placeholder="模板类型" clearable style="width: 200px" class="filter-item"   size="small">
              <el-option v-for="item in tabTypeList"  :key="item.dictKey" :label="item.dictValue" :value="item.dictKey" />
            </el-select>
            <el-select v-model="query.tableTemplateType" placeholder="项目类型" clearable style="width: 200px" class="filter-item"   size="small">
              <el-option v-for="item in tableTemplateTypeList" :key="item.dictKey" :label="item.dictValue" :value="item.dictKey" />
            </el-select>
            <el-button type="primary" @click="searchClick" class="custom-primary-btn"   size="small">搜索</el-button>
            <el-button type="info" @click="clearSearch"   size="small">清空</el-button>
        </div>
        <div class="header-box-right">
          <el-button type="primary" con="el-icon-add" @click="addClick"   size="small">新增</el-button>
          <el-button type="warning" icon="el-icon-sort" @click="handleSort"   size="small">排序</el-button>
          <el-button type="danger" icon="el-icon-delete"  @click="handleDelete"   size="small">删除</el-button>
        </div>
      
    </div>
    <avue-crud
      :option="option"
      :table-loading="loading"
      :data="data"
      :page.sync="page"
      :permission="permissionList"
      :before-open="beforeOpen"
      v-model="form"
      ref="crud"
      @row-update="rowUpdate"
      @row-save="rowSave"
      @row-del="rowDel"
      @search-change="searchChange"
      @search-reset="searchReset"
      @selection-change="selectionChange"
      @current-change="currentChange"
      @size-change="sizeChange"
      @refresh-change="refreshChange"
      @on-load="onLoad"
       :search.sync="query"
    >

  

      
      <template
        slot-scope="scope"
        slot="menu"
      >
  
      <el-button
          type="text"
          icon="el-icon-view"
          size="small"
          @click.stop="viewInfo(scope.row, scope.index)"
        >模版信息
        </el-button>
        <el-button
          type="text"
          icon="el-icon-s-operation"
          size="small"
          @click.stop="handleAdd(scope.row, scope.index)"
        >清表模版
        </el-button>
        <el-button
          type="text"
          icon="el-icon-s-opportunity"
          size="small"
          @click.stop="ElementIdentification(scope.row, scope.index)"
        >元素识别
        </el-button>
      </template>
      <template
        slot-scope="{row}"
        slot="source"
      >
        <div style="text-align:center">
          <i :class="row.source" />
        </div>
      </template>
       <template
            slot-scope="{row}"
            slot="tabType"
          >
                <el-tag
                  size="small"
                  v-for="item in generateTagItems(row.tabType)"
                  :key="item.label"
                  :type="item.type"
                  effect="dark"
                  class="mr-3 custom-ellipse-tag"
                  :class="`custom-tag-type-${item.type}`"
                  >
                 
                  {{ item.label }}
                </el-tag>
        
          </template>
                  <template slot-scope="{row}" slot="projectInfoList">
          
                    <el-tooltip 
                    v-for="item in row.projectInfoList" 
                    :key="item.id"
                    :content="item.projectName"
                    placement="top"
                    :disabled="item.projectName.length<20"
                  >
                    <el-tag  
                      size="small" 
                      type="info"   
                      class="custom-ellipse-tag1 ellipsis-tag"
                      
                    >
                      {{item.projectName}}
                    </el-tag>
                  </el-tooltip>
          </template>

    </avue-crud>

    <!-- 模板信息 -->
      <el-dialog
        class="project-dialog"
        :visible.sync="infoVisible"
        width="65%"
        append-to-body
      >
        <span slot="title">
          <i class="el-icon-view" style="color: #2550A2; margin-right: 10px;"></i>模板信息
        </span>

        <div class="dialog-content" v-loading="infoLoading">
          <!-- 模板基本信息 -->
          <div class="basic-info">
          <div class="flex">
                <div class="info-row">
                  <el-tag
                    size="small"
                    v-for="item in generateTagItems(templateInfo.tabType)"
                    :key="item.label"
                    :type="item.type"
                    effect="dark"
                    class="mr-3 custom-ellipse-tag"
                    :class="`custom-tag-type-${item.type}`"
                    >
                  
                    {{ item.label }}
                  </el-tag>
              </div>
              <div class="info-row ml-4">
                <div class="pro-label">{{ templateInfo.name }}</div>
                <div >{{ templateInfo.tableTemplateTypeName||'项目类型' }}</div>
                <div class="value">
                <span> 创建信息：</span>
                  <span>{{ templateInfo.createUserName }}</span>
                  <span class="ml-4">{{templateInfo.createTime  }}</span>
                </div>
                
              </div>
            </div>
         
            <div class="flex info-row-right">
                  <div class="info-row">
                    <div class="value-num">{{ templateInfo.projectUseNumber||0 }}</div>
                    <div class="label">使用项目数</div>
                  </div>
                <div class="info-row">
                    <span class="value-num">{{ templateInfo.tabCout||0 }}</span>
                    <span class="label">清表数量</span>
                </div>
                <div class="info-row">
                  <span class="value-num">{{ templateInfo.excelUseNumber||0 }}</span>
                  <span class="label">清表使用数量</span>
                </div>
              </div>
          </div>

          <!-- 使用项目明细 -->
          <div class="section-title">使用项目明细</div>
          <div class="project-tags" v-if="templateInfo.projectInfoList">
            <el-tag
              v-for="item in templateInfo.projectInfoList"
              :key="item.id"
              size="small"
              type="info"
              class="custom-ellipse-tag1 ellipsis-tag"
            >
              {{ item.projectName }}
            </el-tag>
          </div>
          <div v-else>暂无数据</div>

          <!-- 模板操作信息 -->
          <div class="section-title" v-if="false">模板操作信息</div>
          <el-table
          v-if="false"
            :data="templateInfo.operationLogs"
            border
            style="width: 100%; margin-top: 10px;"
            :header-cell-style="{ background: '#f5f7fa', color: '#666' }"
          >
            <el-table-column prop="index" label="序号" width="60" align="center">
              <template slot-scope="scope">
                {{ scope.$index + 1 }}
              </template>
            </el-table-column>
            <el-table-column prop="operationDesc" label="操作描述" min-width="200">
              <template slot-scope="scope">
                <span>{{ scope.row.operationDesc }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="operator" label="操作人" width="100">
              <template slot-scope="scope">
                {{ scope.row.operator }}
              </template>
            </el-table-column>
            <el-table-column prop="operateTime" label="操作时间" width="180">
              <template slot-scope="scope">
                {{ scope.row.operateTime }}
              </template>
            </el-table-column>
          </el-table>

          <!-- 分页 -->
          <div class="pagination-container" v-if="templateInfo.total > 0">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 40]"
              :page-size="pageSize"
              layout="total, sizes, prev, pager, next, jumper"
              :total="templateInfo.total"
            />
          </div>
        </div>
      </el-dialog>
      <!-- 排序 -->
           <!-- wbs排序弹窗 -->
        <ContractSort 
         ref="contractSortRef"
         title="清表模板排序"
         :sortProLoad="sortProLoad"
        @confirm="handleSortConfirm"
      />
  </basic-container>
</template>


<script>
import { getList, getDetail, add, update, remove,getExcelInfo } from "@/api/exctab/exceltab";
import { exctabSort } from "@/api/exctab/excelmodel";
import { mapGetters } from "vuex";
import { getDictionary } from "@/api/system/dict";
import { getProjectListPage } from "@/api/manager/projectinfo";
import { getDictionaryBiz } from "@/api/other";
  import ContractSort from './ContractSort.vue'
export default {
  components: {
    ContractSort
  },
  data () {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      search:{
        projectId: '',
        name: '',
        tabType: '',
        tableTemplateType:''

      },
      selectionList: [],
      option: {
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: false,
        refreshBtn:false,
        searchShowBtn: false,
        columnBtn: false,

        border: true,
        index: true,
        viewBtn: false,
        addBtn: false,

        selection: true,
        menuWidth: 400,
        dialogClickModal: false,
        column: [
          {
            label: '创建时间',
            prop: 'createTime',
            width: 150,
            editDisplay: false,
            addDisplay: false,
          },
          {
            label: "模版名称",
            prop: "name",
            search: true,
            rules: [{
              required: true,
              message: "请输入名称",
              trigger: "blur"
            }]
          },
          {
              label: "项目类型",
              type: "select",
               width: 100,
           
              search: true,
              dicUrl: "/api/blade-system/dict-biz/dictionary?code=table_template_type",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "number",
              prop: "tableTemplateType",
              rules: [{
                required: true,
                message: "请选择项目类型",
                trigger: "blur"
              }]
            },
             {
              label: "模板类型",
              type: "select",
               width: 120,
              slot: true,
              search: true,
              dicUrl: "/api/blade-system/dict/dictionary?code=wbs_type",
              props: {
                label: "dictValue",
                value: "dictKey"
              },
              dataType: "number",
              prop: "tabType",
              rules: [{
                required: true,
                message: "请选择项目类型",
                trigger: "blur"
              }]
            },

          {
            label: "表数量",
            prop: "tabCout",
            width: 80,
            editDisplay: false,
            addDisplay: false,
            rules: [{
              message: "请输入表数量",
              trigger: "blur",
            }]
          },
          {
            label: "项目名称",
            prop: "projectInfoList",
            display: false,
            search: true,
            slot:true,
          },
        ]
      },
      data: [],
      tableTemplateTypeList: [],
      projectList:[],
      infoVisible: false,
      infoLoading: false,

      templateInfo: {
       
      },
      currentPage: 1,
      pageSize: 20,
      tabTypeList:[],
      sortList  : [],
      sortListAll:[],

      sortProLoad:false
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList () {
      return {
        addBtn: this.vaildData(this.permission.exceltab_add, false),
        viewBtn: this.vaildData(this.permission.exceltab_view, false),
        delBtn: this.vaildData(this.permission.exceltab_delete, false),
        editBtn: this.vaildData(this.permission.exceltab_edit, false)
      };
    },
    ids () {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
    getTableTemplateTypeList(){
           let code = "table_template_type";
            getDictionaryBiz({
                code,
            }).then((res) => {
                    this.tableTemplateTypeList = res.data.data;
            });

    },
    getTabTypeList(){
           let code = "wbs_type";
            getDictionary({
                code,
            }).then((res) => {
                    this.tabTypeList = res.data.data;
            });

    },
    getProjectListPage() {
      let params = {};
      params.page = this.currentPage;
      params.size = this.pageSize;
      getProjectListPage(params).then((res) => {
        this.projectList = res.data.data.records;
      });
    },
    onLoad (page, params = {}) {
      this.loading = true;
    },

    generateTagItems(wbsTypes){
       const typeToLabelMap = {
        1: '质检',
        2: '试验',
        3: '日志',
        4: '计量',
        5: '征拆',
        6: '底层节点',
       
    };
      let tagItems = [];
         // 如果 wbsTypes 不是数组，则将其转换为数组
    if (!Array.isArray(wbsTypes)) {
        wbsTypes = [wbsTypes];
    }
      wbsTypes.forEach(type => {
        // 检查type是否在映射关系中存在
        if (typeToLabelMap.hasOwnProperty(type)) {
            // 如果存在，则创建一个新的对象并添加到tagItems数组中
            tagItems.push({
                type: type,
                label: typeToLabelMap[type]
            });
        }
    });
     return tagItems;
  },

    handleAdd (row) {
      this.$router.push('/excel/excelmodel/' + row.id);
    },
    ElementIdentification (row) {
      this.$router.push('/excels/ElementIdentification/' + row.id);
    },
    rowSave (row, done, loading) {
      add(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate (row, index, done, loading) {
      update(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    rowDel (row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    handleDelete () {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return remove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    beforeOpen (done, type) {
      if (["edit", "view"].includes(type)) {
        getDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset () {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange (params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    selectionChange (list) {
      this.selectionList = list;
    },
    selectionClear () {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange (currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange (pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange () {
      this.onLoad(this.page, this.query);
    },
    onLoad (page, params = {}) {
      console.log(page.currentPage, params.pageSize);
      this.query.parentId = 0;
      this.loading = true;
      getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records;
        this.loading = false;
        this.selectionClear();
      });
    },
    getProjectList () {
      getProjectListPage({
        current:1,
        size:999,
        ...this.searchForm

      }).then((res) => {
        this.projectList = res.data.data.records;
      })
    },
    //查看模板信息
    viewInfo(row,index){
      this.infoVisible = true;
      this.getExcelInfoData(row.id)
      

    },
    handleSizeChange(val) {
      this.pageSize = val;
      this.currentPage = 1;
      // 可重新请求数据
    },
    handleCurrentChange(val) {
      this.currentPage = val;
      // 可重新请求数据
    },
    getExcelInfoData(id){
      this.infoLoading = true;
       getExcelInfo({id:id}).then((res) => {
             if(res.data.code==200){
                this.templateInfo = res.data.data;
            }else{
                 this.templateInfo = {}
            }
    }).finally(() => {
            this.infoLoading = false;
        });
  },
  searchClick(){
     this.onLoad(this.page,this.query);
  },
  clearSearch () {
    this.query = {}
   this.onLoad(this.page,this.query);
  },
  addClick(){
         this.$refs.crud.rowAdd();
  },
  //排序
handleSort(){
    this.sortProLoad = true;
      getList(1, 1000,{parentId:0}).then(res => {
        const data = res.data.data;
        this.sortListAll = data.records;
         this.sortList = JSON.parse(JSON.stringify(this.sortListAll));
  

          this.$nextTick(() => {
            this.$refs.contractSortRef.show(this.sortList);
          })
      }).finally(()=>{
        this.sortProLoad = false;
      })
    
    
  },
   handleSortConfirm(sortedList) {
      // 这里处理排序后的数据
      console.log('排序后的列表:', sortedList);
      // TODO: 调用接口保存排序结果
      this.sortList = [...sortedList];
        const ids = this.sortList.map(item => item.id);
     this.saveSort(ids);

    },
    saveSort(ids){

      let allIds=ids.join(',');
        
        exctabSort({ids:allIds}).then((res) => {
                    this.sortProLoad= false;
                    if(res.data.code==200){
                        this.$message.success(res.data.msg)
                      
                                 this.onLoad(this.page);
                    }else{
                        this.$message.error(res.data.msg)
                    }
                })
      


    }
  
},

  created() { 
    this.getTableTemplateTypeList()
    this.getProjectList()
    this.getTabTypeList()
  },
};
</script>

<style scoped lang="scss">
.ellipsis-tag {
  max-width:300px; /* 设置最大宽度 */
  overflow: hidden;
  margin-right: 4px;

  
  .el-tag__content {
    display: inline-block;
    max-width: 100%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
  }
}
.dialog-content {
  padding: 20px;
  font-size: 14px;

  .basic-info {
    margin-bottom: 20px;
    display: flex;
    justify-content: space-between;
    align-items: center;
    .info-row-right{
      line-height: 30px;
    }
    .info-row {
      display: flex;
      flex-direction:column ;
      margin-bottom: 10px;
      .label {
        width: 100px;
        color: #666;
         text-align: center;
      }
      .pro-label{
        font-weight: bold;
        font-size: larger;
      }
      .value {
        flex: 1;
      }
      .value-num{
        font-size: larger;
        font-weight: bold;
        color: rgba(37, 80, 162, 1);
        text-align: center;
      }
    }
  }

  .section-title {
    font-weight: bold;
    margin: 15px 0 10px;
    background-color: #E0E0E0;
    font-size: larger;
    padding-left: 15px;
    padding: 5px 0 5px 15px;

    line-height: 30px;
    color: rgba(118, 118, 118, 1);
    border-radius: 5px;
  }

  .project-tags {
    display: flex;
    flex-wrap: wrap;
    gap: 8px;
    margin-bottom: 20px;
  }

  .pagination-container {
    margin-top: 20px;
    text-align: center;
  }
}
.ml-4{
  margin-left: 4px;
}
.filter-item{
  margin-right: 10px;
}
.search-box{
  display: flex;
  justify-content: space-between;
}
</style>
