<template>
  <basic-container>
        <div class="search-box">
        <div class="search-box-left">
            <el-input v-model="query.wbsName" 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.wbsType" 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-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"
            size="small"
            icon="el-icon-plus"
        
        
            @click="handleAdd"
          >新增
          </el-button>
                <el-button
            type="warning"
            size="small"
            icon="el-icon-sort"
    
      
            @click="handleSort"
          >排序
          </el-button>
              <el-button
            type="danger"
            size="small"
            icon="el-icon-delete"
          
            v-if="permission.wbsinfo_delete"
            @click="handleDelete"
          >删 除
          </el-button>
          <!-- 新增元素按钮 -->
          <el-button
            size="small"
            style="background-color:#FFA042;color:white;font-weight:bold;border-color: #FFA042;"
            plain
            v-if="permission.wbsinfo_delete"
            @click="handleElement"
          >元素库
          </el-button>
          <el-button
            size="small"
            style="background-color:#2550A2;color:white;font-weight:bold;border-color: #2550A2;"
            plain
            v-if="permission.wbsinfo_delete"
            @click="handleParameter"
          >参数库
          </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="search"
    >

<template slot-scope="{disabled,size}" slot="projectInfoListSearch">
      <el-select v-model="search.projectId" placeholder="项目名称" filterable  clearable>
          <el-option
            v-for="item in projectList"
            :key="item.id"
            :label="item.projectAlias"
            :value="item.id">
          </el-option>
        </el-select>
  </template>
      <template slot="menuRight">
         
      </template>
      <template
        slot-scope="{row,index}"
        slot="menu"
      >
        <el-button
          type="text"
          icon="el-icon-edit"
          size="mini"
          v-if="permission.wbsinfo_tree_edit"
          @click="toEdit(row,index)"
        >编辑wbs库</el-button>
      </template>
       <template
            slot-scope="{row}"
            slot="wbsType"
          >
            <!-- <el-tag>{{ row.wbsType }}</el-tag> -->
                <el-tag
                  size="small"
                  v-for="item in generateTagItems(row.wbsType)"
                  :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="true"
                  >
                    <el-tag  
                      size="small" 
                      type="info"   
                      class="custom-ellipse-tag1 ellipsis-tag"
                      
                    >
                      {{item.projectName}}
                    </el-tag>
                  </el-tooltip>
          </template>
    </avue-crud>
           <!-- wbs排序弹窗 -->
        <ContractSort 
         ref="contractSortRef"
         title="wbs排序弹窗"
         :sortProLoad="sortProLoad"
        @confirm="handleSortConfirm"
      />
  </basic-container>
</template>

<script>
import { getList, getDetail, add, update, remove,sortWbs } from "@/api/manager/wbsinfo";
import { mapGetters } from "vuex";
  import { getDictionary } from "@/api/system/dict";
  import ContractSort from './ContractSort.vue'
import { getProjectListPage } from "@/api/manager/projectinfo";

export default {
  components: {
    ContractSort
  },
  data () {
    return {
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {
        menuWidth: 300,
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchMenuSpan: 6,
 
        border: true,
        index: true,
        viewBtn: true,
          addBtn: false,
        selection: true,
         refreshBtn:false,
        searchShowBtn: false,
        columnBtn: false,
        dialogClickModal: false,
          searchShow: false,
        column: [
          {
            label: "创建时间",
            prop: "createTime",
            editDetail: true,
            addDisabled: true,
               hide: true,
      
          },
          {
            label: "wbs名称",
            prop: "wbsName",
            search: true,
            width: 180,
        
       
       
            rules: [{
              required: true,
              message: "请输入wbs名称",
              trigger: "blur"
            }]
          },
          {
            label: "划分类型",
            slot: true,
              search: true,
              width: 120,
        
          
           
           
           
            type: "select",
            dicUrl: "/api/blade-system/dict/dictionary?code=wbs_type",
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            dataType: "number",
            prop: "wbsType",
            rules: [{
              required: true,
              message: "请选择划分类型",
              trigger: "blur"
            }],
           
          },
          {
            label: "是否启用",
            prop: "status",
            hide: true,
      
            rules: [{
              required: true,
              message: "是否启用",
              trigger: "blur"
            }],
            type: "radio",
            dicData: [
              {
                label: "否",
                value: 0
              },
              {
                label: "是",
                value: 1
              }
            ],
          },
           {
            label: "引用项目",
            prop: "projectInfoList",
            display: false,
            search: true,
            slot:true,
          },
   
        ]
      },
      data: [],
      search:{
        wbsName: '',
        wbsType: '',
        projectId:''
      },
       wbsTypeList:[],

       sortProLoad:false,
       wbsList:[],
       sortWbsList:[],
       projectList:[],
       tabTypeList:[],

    };
  },
  created () {
    this.getTabTypeList()
    this.getWbsList()
    this.getProjectList()
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList () {
      return {
        addBtn: this.vaildData(this.permission.wbsinfo_add, false),
        viewBtn: this.vaildData(this.permission.wbsinfo_view, false),
        delBtn: this.vaildData(this.permission.wbsinfo_delete, false),
        editBtn: this.vaildData(this.permission.wbsinfo_edit, false)
      };
    },
    ids () {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  methods: {
  getProjectList () {
      getProjectListPage({
        current:1,
        size:999,
        ...this.searchForm

      }).then((res) => {
        this.projectList = res.data.data.records;
      })
    },
  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;
  },
     getTabTypeList(){
           let code = "wbs_type";
            getDictionary({
                code,
            }).then((res) => {
                    this.tabTypeList = res.data.data;
            });

    },
      //点击元素库
    handleElement(){
      console.log('元素库');
      this.$router.push({
        path: '/wbs/element',
      })
    },
    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: "操作成功!"
          });
        });
    },
    handleAdd(row) {
      
        this.$refs.crud.rowAdd();
      },
    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 = {}) {
      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();
      });
    },

    toEdit (row) {
      console.log(row);
      this.$router.push({
        path: '/wbs/edit',
        query: {
          id: row.id,
          type: row.wbsType
        }
      })
      //this.$router.push('/wbs/edit/' + row.id);
    },
    //点击参数库
    handleParameter(){
       this.$router.push('/wbs/parameter');
    },
    getWbsList(){
      getList(1, 1000).then(res => {
        const data = res.data.data;
        
        this.wbsList=data['records']
      });
    },
    //排序
    handleSort(){
         this.sortWbsList = JSON.parse(JSON.stringify(this.wbsList));
        this.sortTitle = '合同段排序';

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

    },
    saveSort(ids){
        sortWbs(ids).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)
                    }
                })
      


    },
    searchClick(){ 
      this.onLoad(this.page,this.query);
    },
    clearSearch(){
      this.query = {};
      this.onLoad(this.page,this.searchParams);
    }
  }
};
</script>

<style scoped lang="scss">
.search-box{
  display: flex;
  justify-content: space-between;
  .search-item{
    margin-right: 10px;
    margin-left: 10px;
  }
 
}
.filter-item{
  margin-right: 10px;
}
</style>
