<template>
  <div class="app-container">
    <el-card>
        <el-row :gutter="6">
          <el-col :xs="24" :md="4">
            <el-select v-model="listQuery.qualification__ssbm__name" placeholder="所属单位" @change="handleFilter2" clearable style="width: 100%;">
    <el-option
      v-for="item in groupBy.qualification__ssbm__name"
            :key="item.value"
            :label="item.text"
            :value="item.value">
    </el-option>
  </el-select>
          </el-col>
          <el-col :xs="24" :md="8">
          <el-input
            v-model="listQuery.search"
            placeholder="资质/服务"
            style="width: 100%;"
            class="filter-item"
            @keyup.enter.native="handleFilter"
          />
          </el-col>
          <el-col :xs="24" :md="6">
          <el-button
            class="filter-item"
            type="primary"
            icon="el-icon-search"
            @click="handleFilter"
          >搜索</el-button>
          <el-button
            class="filter-item"
            type="primary"
            icon="el-icon-refresh-left"
            @click="resetFilter"
          >重置</el-button>
          </el-col>
        </el-row>
        <div style="margin-top:10px">
          <el-button type="primary" style="display:none" icon="el-icon-plus" @click="handleAdd" v-if="checkPermission(['qualification_create'])">新增</el-button>
          
          <el-popover
  placement="top"
  width="160"
  v-if="checkPermission(['qualification_import'])"
  v-model="popovervisible"
  >
  <p>导入资质excel.</p>
    <el-upload
  :action="upUrl"
  :on-success="handleUploadSuccess"
  accept=".xlsx"
  :headers="upHeaders"
  :show-file-list ="false"
  >
  <div style="text-align: left; margin: 0;">
  <el-link
            href="/media/muban/qualification.xlsx"
            target="_blank"
            @click="popovervisible = false"
            type="primary"
          >下载模板</el-link>
  <el-button size="small" type="primary" @click="popovervisible = false">上传导入</el-button>
  </div>
</el-upload>

  
  <el-button slot="reference">导入资质</el-button>
  
</el-popover>
 <el-button @click="delAll()"  v-if="checkPermission(['qualification_deletes'])">批量删除</el-button>
        </div>
    </el-card>
    <el-card style="margin-top:10px">
        <el-table
          v-loading="listLoading"
          :data="tableData"
          :span-method="objectSpanMethod"
          style="width: 100%;margin-top:10px;"
          border
          fit
         
          stripe
          highlight-current-row
       
          ref="filterTable"
           @selection-change="handleSelectionChange"
          @filter-change="filterChange"
       
        >
         <el-table-column
      type="selection"
      width="55">
    </el-table-column>
          <el-table-column align="center"  label="所属单位" 
          >
            <template style="text-align:left;" slot-scope="scope">{{ scope.row.qualification_.bm_.name }}</template>
          </el-table-column>
          <el-table-column header-align="center"   label="CMA资质">
            <template style="text-align:left;" slot-scope="scope">
              <span style="margin-top:0px"  v-html="showlight(scope.row.qualification_.cma)"></span>
              </template>
          </el-table-column>
          <el-table-column header-align="center"   label="CNAS资质">
            <template style="text-align:left;" slot-scope="scope">
              <span  v-html="showlight(scope.row.qualification_.cnas)"></span>
              </template>
          </el-table-column>
           <el-table-column width="800" header-align="center"  label="检验检测相关其他资质及校准资质">
          <el-table-column width="300" header-align="center"  label="其它资质" >
            <template style="text-align:left;" slot-scope="scope">
              <span  v-html="showlight(scope.row.name)"  ></span>
              </template>
          </el-table-column>
          <el-table-column width="500" header-align="center"  label="资质范围" >
            <template style="text-align:left;" slot-scope="scope">
              <span  v-html="showlight(scope.row.description)" ></span>
              </template>
          </el-table-column>
           </el-table-column>
          <el-table-column header-align="center"   label="主要服务">
            <template style="text-align:left;" slot-scope="scope">
              <span  v-html="showlight(scope.row.qualification_.service)"></span>
              </template>
          </el-table-column>
        
        </el-table>
    </el-card>
     

   
  </div>
</template>
<style >
.el-table-filter{
  width:400px;
  max-height: 300px;
  overflow-y: auto;
}
.el-table .cell {
  white-space: pre-line;
}
</style>
<script>
import { getQualificationList,getQualificationotherList,deletes, getQualificationGroup1, createQualification, updateQualification, deleteQualification, importQualification } from "@/api/qualification";
import checkPermission from "@/utils/permission"
import {getOrgList} from "@/api/org";
import { upUrl, upHeaders } from "@/api/file"
import Pagination from "@/components/Pagination" // secondary package based on el-pagination
const defaultCMA = {
  id: null,
  cma:null,
  cnas:null,
  other:null,
  service:null

};
const dflistQuery = {
   pageoff:true,
  search:''
}
export default {
  components: {  },
  data() {
    return {
      
delarr:[],
      upHeaders: upHeaders(),
      upUrl: upUrl(),
      groupBy:{qualification__ssbm__name:[]},
      tableData: [],
        rowIndex: '-1',
      OrderIndexArr: [],
      hoverOrderArr: [],
      listLoading: true,
      listQuery:  dflistQuery,
      enabledOptions: [
        { key: "true", display_name: "激活" },
        { key: "false", display_name: "禁用" }
      ],
      dialogVisible: false,
      dialogType: "new",
      popovervisible: false,
      rule1:{
        sszx: [{
          required: true,
          message: '请填写',
          trigger: 'blur'
        }],
        cma: [{
          required: true,
          message: '请填写',
          trigger: 'blur'
        }],
        cna: [{
          required: true,
          message: '请填写',
          trigger: 'blur'
        }],
        other: [{
          required: true,
          message: '请填写',
          trigger: 'blur'
        }],
        service: [{
          required: true,
          message: '请填写',
          trigger: 'blur'
        }],
      },
    };
  },
  computed: {},
  watch: {
  },
  created() {
    this.getList()
    this.getGroup()
  },
  
  methods: {
    checkPermission,
    handleUploadSuccess(res, file) {
        const loading = this.openLoading()
        let data = {path:res.data.path}
        importQualification(data).then(res=>{
      this.$message({
          message: '导入成功',
          type: 'success'
        })
        loading.close()
        this.resetFilter()
        }).catch(error=>{loading.close()})
    },
    getList() {
      this.listLoading = true;
      getQualificationotherList(this.listQuery).then(response => {
        if (response.data) {
         
  
          this.tableData = response.data
        let OrderObj = {}
        
        this.tableData.forEach((element, index) => {
            element.rowIndex = index
            if (OrderObj[element.qualification_.id]) {
              OrderObj[element.qualification_.id].push(index)
            } 
            else {
              OrderObj[element.qualification_.id] = []
              OrderObj[element.qualification_.id].push(index)
            }
            
        })
        var indexarrs=[]
    // 将数组长度大于1的值 存储到this.OrderIndexArr（也就是需要合并的项）
        for (let k in OrderObj) {
          if (OrderObj[k].length > 1) {
            indexarrs.push(OrderObj[k])
          }
        }
        }
        this.OrderIndexArr=indexarrs
        this.listLoading = false
       
      })
      console.log(this.OrderIndexArr)
    },
   // 合并单元格
      objectSpanMethod({row,column,rowIndex,columnIndex}) {
        if (columnIndex === 1  ||  columnIndex === 2||  columnIndex === 3|| columnIndex === 6) {
          for (let i = 0; i < this.OrderIndexArr.length; i++) {
            let element = this.OrderIndexArr[i]
            for (let j = 0; j < element.length; j++) {
              let item = element[j]
              if (rowIndex == item) {
                if (j == 0) {
                  return {
                    rowspan: element.length,
                    colspan: 1
                  }
                } else if (j != 0) {
                  return {
                    rowspan: 0,
                    colspan: 0
                  }
                }
              }
            }
          }
        }
        
      },


 handleSelectionChange(val) {
                this.multipleSelection = val;
            },
     delAll() {
         this.$confirm("确认删除?", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "error",
      })
        .then(async () => {
        const lengths = this.multipleSelection.length;
        for (let i = 0; i < lengths; i++) {
               this.delarr.push(this.multipleSelection[i].id);
         }
     
      let data = { ids: this.delarr };
      deletes(data)
        .then((res) => {
          this.$message({
            message: "删除成功",
            type: "success",
          });
           this.getList();
        })
     })
        .catch((err) => {
          console.error(err);
        });
    },
            


    getGroup() {
      for (let key in this.groupBy) {
        let data = Object.assign({}, this.listQuery);
        data.group_by = key;
        getQualificationGroup1(data).then((response) => {
          this.groupBy[key] = response.data;
          console.log(this.groupBy);
        });
      }
    },
    resetFilter() {
      this.listQuery = Object.assign({}, dflistQuery),
      this.getList()
      this.getGroup()
    },
    handleFilter() {
      this.getList()
      this.getGroup()
    },
    handleFilter2() {
      this.getList()
      this.getGroup()
    },
    handleAdd() {
      this.formData = Object.assign({}, defaultCMA)
      this.dialogType = "new"
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs["Form"].clearValidate()
      })
    },
  
   
    handleEdit(scope) {
      this.formData = Object.assign({}, scope.row) // copy obj
      this.dialogType = "edit"
      this.dialogVisible = true
      this.$nextTick(() => {
        this.$refs["Form"].clearValidate()
      })
    },
    handleDelete(scope) {
      this.$confirm("确认删除?", "警告", {
        confirmButtonText: "确认",
        cancelButtonText: "取消",
        type: "error"
      })
        .then(async () => {
          var res = await deleteQualification(scope.row.id);
          this.tableData.results.splice(scope.row.index, 1);
          this.$message.success('成功');
        })
        .catch(err => {
          console.error(err);
        });
    },
    filterChange (obj) { 
for(let key in obj){
  this.listQuery[key] = obj[key][0]
}

this.getList()
},
    async confirm(form) {
      this.$refs[form].validate(valid => {
        if (valid) {
          const isEdit = this.dialogType === "edit";
          if (isEdit) {
            updateQualification(this.formData.id, this.formData).then(res => {
              if (res.code >= 200) {
                this.getList();
                this.dialogVisible = false;
                this.$message.success('成功')
              }
            });
          } else {
            createQualification(this.formData).then(res => {
              if (res.code >= 200) {
                this.getList();
                this.dialogVisible = false;
                this.$message.success('成功')
              }
            });
          }
        } else {
          return false;
        }
      });
    },
     showlight(val) {
val = val + "";
  if (this.listQuery.search !== "") {
    let  searchList = this.listQuery.search.split(' ');
    let reg = null;
    for(var i=0;i<searchList.length;i++){
      reg=new RegExp(searchList[i],"g");
      val = val.replace(reg, '<span style="color:red;font-weight:bold">' + searchList[i] + "</span>");
    }
    return val
  } else {
    return val;
  }
    },


    
  }
};
</script>
