<template>
  <div>
    <el-table
      v-loading="listLoading"
      :data="tableData.results"
      style="width: 100%;"
      border
      fit
      stripe
      highlight-current-row
      height="380"
      @row-click="rowClick"
    >
      <el-table-column type="index" width="50" />
      <el-table-column label="单元名称">
        <template slot-scope="scope" >{{ scope.row.name }}</template>
      </el-table-column>
      <el-table-column label="单元描述">
        <template slot-scope="scope" >{{ scope.row.description }}</template>
      </el-table-column>
      <el-table-column label="采用标准">
        <template slot-scope="scope" >{{ scope.row.standard_.fullname }}</template>
      </el-table-column>
      <el-table-column label="创建时间">
        <template slot-scope="scope">
          <span>{{ scope.row.create_time }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作">
        <template slot-scope="scope">
          <el-button
            type="danger"
            size="small"
            :disabled="!checkPermission(['certapps_update'])"
            @click="handleDelete(scope)"
          >删除</el-button>
        </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-form ref="elForm" :model="formData" :rules="rules" size="medium" label-width="80px" style="margin-top:10px">
      <el-col :xs="24" :md="12">
        <el-form-item label="实施规则" prop="implementrule">
          <el-select
            v-model="formData.implementrule"
            placeholder="请选择实施规则"
            clearable
            :style="{width: '100%'}"
            @change="changeTypeOptions"
          >
            <el-option
              v-for="(item, index) in implementruleOptions"
              :key="index"
              :label="item.fullname"
              :value="item.id"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :xs="24" :md="12">
        <el-form-item label="单元类型" prop="unittype">
          <el-select
            v-model="formData.unittype"
            placeholder="请选择单元类型"
            clearable
            :style="{width: '100%'}"
            @change="changeUnit"
          >
            <el-option
              v-for="(item, index) in unittypeOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :xs="24" :md="12">
        <el-form-item label="采用标准" prop="standard">
          <el-input
            v-model="formData.standard_.fullname"
            placeholder="请输入采用标准"
            readonly
            clearable
            :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
      </el-col>
      <el-col :xs="24" :md="12">
        <el-form-item label="检测机构" prop="testorg">
          <el-select v-model="formData.testorg" placeholder="请选择检测机构" clearable :style="{width: '100%'}">
            <el-option
              v-for="(item, index) in testorgOptions"
              :key="index"
              :label="item.label"
              :value="item.value"
              :disabled="item.disabled"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-col>
      <el-col :xs="24" :md="8">
        <el-form-item label="单元名称" prop="name">
          <el-input
            v-model="formData.name"
            placeholder="请输入单元名称"
            clearable
            :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
      </el-col>
      <el-col :xs="24" :md="16">
        <el-form-item label="单元描述" prop="description">
          <el-input
            v-model="formData.description"
            placeholder="请输入单元描述"
            clearable
            :style="{width: '100%'}"
          ></el-input>
        </el-form-item>
      </el-col>
      <el-col :span="24">
        <el-form-item size="large">
          <el-button type="primary" @click="createNew">创建新记录</el-button>
          <el-button type="primary" @click="updateNow">保存</el-button>
          <el-button @click="resetForm">重置</el-button>
        </el-form-item>
      </el-col>
    </el-form>
  </div>
</template>
<script>
import { getImplementRuleList, getUnitTypeList } from "@/api/implementrule"
import { getUnitList, deleteUnit, createUnit, updateUnit } from "@/api/unit";
import { getDictList } from "@/api/dict";
import Pagination from "@/components/Pagination";
import checkPermission from "@/utils/permission";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { genTree } from "../../utils";
export default {
  name: "Productunit",
  components: { Pagination, Treeselect },
  props:['certapp'],
  data() {
    return {
      tableData: { count: 0 },
      listLoading: true,
      listQuery: {
        page: 1,
        page_size: 20,
        certapp:this.certapp
      },
      formData: {
        certapp:this.certapp,
        implementrule: undefined,
        unittype: undefined,
        standard: undefined,
        standard_:{},
        testorg: undefined,
        name: undefined,
        description: undefined,
      },
      rules: {
        implementrule: [
          {
            required: true,
            message: "请选择实施规则",
            trigger: "change",
          },
        ],
        unittype: [
          {
            required: true,
            message: "请选择单元类型",
            trigger: "change",
          },
        ],
        standard: [],
        testorg: [],
        name: [
          {
            required: true,
            message: "请输入单元名称",
            trigger: "blur",
          },
        ],
        description: [
          {
            required: true,
            message: "请输入单元描述",
            trigger: "blur",
          },
        ],
      },
      implementruleOptions: [
      ],
      unittypeOptions: [
      ],
      testorgOptions: [
      ],
    };
  },
  watch:{
    'formData.implementrule': function(val){
      this.changeTypeOptions()
    },
  },
  created() {
    this.getList();
    this.getImplementRuleOptions()
  },
  methods: {
    checkPermission,
    getList() {
      this.listLoading = true;
      getUnitList(this.listQuery).then((response) => {

        if (response.data) {
          
          this.tableData = response.data;
          
        }
        this.listLoading = false;
      });
    },
    resetFilter() {
      this.listQuery = {
        page: 1,
        page_size: 20,
      };
      this.getList();
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },
    handleCreate(item, index) {
      this.$router.push({
        name: "CertappForm",
        params: { kind: item.code, action: "create" },
      });
    },
    handleUpdate(scope) {
      this.$router.push({
        name: "CertappForm",
        params: { action: "update", kind: scope.row.cert_field_.code },
        query: { id: scope.row.id },
      });
    },
    handleDelete(scope) {
      this.$confirm("确定删除?", "警告", {
        // confirmButtonText: '确定',
        // cancelButtonText: '取消',
        type: "warning",
      }).then(() => {
        deleteUnit(scope.row.id).then((res) => {
          this.$message.success("成功");
          this.getList();
        });
      }).catch(()=>{});
    },
    createNew() {
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        // TODO 提交表单
        createUnit(this.formData).then(res=>{
          this.getList()
          this.$message.success('成功')
        })
      })
    },
    updateNow(){
      this.$refs['elForm'].validate(valid => {
        if (!valid) return
        // TODO 提交表单
        updateUnit(this.formData.id, this.formData).then(res=>{
          this.getList()
          this.$message.success('成功')
        })
      })
    },
    resetForm() {
      this.$refs['elForm'].resetFields()
    },
    getImplementRuleOptions(){
      var query = {ccc_list:this.certapp.cccpv_class}
      getImplementRuleList(query).then(res=>{
        this.implementruleOptions = res.data.results
      })
    },
    changeTypeOptions(){
      getUnitTypeList({implementrule:this.formData.implementrule}).then(res=>{
        this.unittypeOptions = genTree(res.data)
      })
    },
    changeUnit(val){
      let obj = {};
      obj = this.unittypeOptions.find((item)=>{//这里的userList就是上面遍历的数据源
          return item.id === val;//筛选出匹配数据
      });
      this.formData.name = obj.name
      this.formData.standard = obj.standard
      this.formData.standard_ = obj.standard_
    },
    rowClick(row, column, event){
      this.formData = Object.assign({}, row);
    }
  },
};
</script>
