<template>
  <div class="app-container">
        <el-row :gutter="6">
          <el-col :xs="24" :md="4">
            <el-select v-model="listQuery.sszx" placeholder="所属单位" @change="handleFilter2" clearable style="width: 100%;">
    <el-option
      v-for="item in groupBy.sszx"
      :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" icon="el-icon-plus" @click="handleAdd" v-if="checkPermission(['qualification_create'])">新增</el-button>
          <!-- <el-popover
  placement="top"
  width="160"
  v-if="checkPermission(['ability_import'])"
  v-model="popovervisible"
  >
  <p>导入能力列表压缩包.</p>
  <div style="text-align: left; margin: 0;">
    <el-upload
  :action="upUrl"
  :on-success="handleUploadSuccess"
  accept=".rar,.zip"
  :headers="upHeaders"
  :show-file-list ="false"
  >
  <el-button size="small" type="primary" @click="popovervisible = false">上传导入</el-button>
</el-upload>
  </div>
  
  <el-button slot="reference">导入资质</el-button>
</el-popover> -->
        </div>
        <el-table
          v-loading="listLoading"
          :data="tableData.results"
          style="width: 100%;margin-top:10px;"
          border
          fit
          stripe
          highlight-current-row
          max-height="700"
          ref="filterTable"
          @filter-change="filterChange"
        >
          <el-table-column type="index" width="50" />
          <el-table-column  label="所属单位"
          prop="sszx"
           column-key="sszx"
          :filters="groupBy.sszx"
          :filter-multiple="false"
          >
            <template slot-scope="scope">{{ scope.row.sszx }}</template>
          </el-table-column>
          <el-table-column label="CMA资质">
            <template slot-scope="scope">
              <span  v-html="showlight(scope.row.cma)"></span>
              </template>
          </el-table-column>
          <el-table-column  label="CNAS资质">
            <template slot-scope="scope">
              <span  v-html="showlight(scope.row.cnas)"></span>
              </template>
          </el-table-column>
          <el-table-column  label="其它资质">
            <template slot-scope="scope">
              <span  v-html="showlight(scope.row.other)"></span>
              </template>
          </el-table-column>
          <el-table-column  label="主要服务">
            <template slot-scope="scope">
              <span  v-html="showlight(scope.row.service)"></span>
              </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-button
                :disabled="!checkPermission(['qualification_update'])"
                type="primary"
                size="small"
                icon="el-icon-edit"
                @click="handleEdit(scope)"
              />
              <el-button
                :disabled="!checkPermission(['qualification_delete'])"
                type="danger"
                size="small"
                icon="el-icon-delete"
                @click="handleDelete(scope)"
              />
            </template>
          </el-table-column>
        </el-table>

        <pagination
          v-show="tableData.count>0"
          :total="tableData.count"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.page_size"
          @pagination="getList"
        />

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑':'新增'">
      <el-form ref="Form" :model="formData" label-width="100px" label-position="right" :rules="rule1">
        <el-form-item label="所属单位" prop="sszx">
          <el-input v-model="formData.sszx" placeholder="所属单位" />
        </el-form-item>
        <el-form-item label="CMA资质" prop="cma">
          
          <el-input v-model="formData.cma" placeholder="CMA资质" type="textarea" :autosize="{ minRows: 2, maxRows: 4}"/>
        </el-form-item>
        <el-form-item label="CNAS资质" prop="cnas">
          <el-input v-model="formData.cnas" placeholder="CNAS资质" type="textarea" :autosize="{ minRows: 2, maxRows: 4}"/>
        </el-form-item>
        <el-form-item label="其它资质" prop="other">
          <el-input v-model="formData.other" placeholder="其它资质" type="textarea" :autosize="{ minRows: 2, maxRows: 4}"/>
        </el-form-item>
        <el-form-item label="主要服务" prop="service">
          <el-input v-model="formData.service" placeholder="主要服务" type="textarea" :autosize="{ minRows: 2, maxRows: 4}"/>
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirm('Form')">确认</el-button>
      </div>
    </el-dialog>
  </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, getQualificationGroup, createQualification, updateQualification, deleteQualification } from "@/api/qualification";
import checkPermission from "@/utils/permission"
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 = {
  page: 1,
  page_size: 20,
  search:''
}
export default {
  components: { Pagination },
  data() {
    return {
      formData: {
  id: null,
  cma:null,
  cnas:null,
  other:null,
  service:null

},
      upHeaders: upHeaders(),
      upUrl: upUrl(),
      groupBy:{sszx:[]},
      tableData: {count:0},
      listLoading: true,
      listQuery: Object.assign({}, 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;
      getQualificationList(this.listQuery).then(response => {
        if (response.data) {
          this.tableData = response.data
        }
        this.listLoading = false
      })
    },
    getGroup() {
      for(let key in this.groupBy){
        let data = Object.assign({}, this.listQuery)
        data.group_by = key
        getQualificationGroup(data).then(response => {
        this.groupBy[key] = response.data
      })
      }
    },
    resetFilter() {
      this.listQuery = Object.assign({}, dflistQuery),
      this.getList()
      this.getGroup()
    },
    handleFilter() {
      this.listQuery.page = 1
      this.getList()
      this.getGroup()
    },
    handleFilter2() {
      this.listQuery.page = 1
      this.getList()
    },
    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.listQuery.page=1
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(' ')
    for(var i=0;i<searchList.length;i++){
      val = val.replace(searchList[i], '<span style="color:red;font-weight:bold">' + searchList[i] + "</span>");
    }
    return val
  } else {
    return val;
  }
    },
  }
};
</script>
