<template>
  <div class="app-container">
    <div class="app-container-search main-bgcolor main-radius">
      <h1 class="">检查报告模板</h1>
      <br />
      <!-- 搜索工作栏 -->
      <SearchInfo
          ref="searchForm"
          :searchFormParam="{queryParams , dataSource}"
          :showSearch.sync="showSearch"
          @handleQuery="handleQuery"
          @resetQuery="resetQuery"
      ></SearchInfo>
    </div>
    <div class="app-container-list main-bgcolor main-radius shopping">
      <div class="shopping-top">
        <div class="shopping-title">控制器类型列表</div>
        <el-button class="shopping-add-btn" type="primary" plain @click="handleAdd"
          v-hasPermi="['configure:inspection-template:create']">添加</el-button>
      </div>
      <!-- 列表 -->
      <el-table v-loading="loading" :data="list">
        <el-table-column label="编号" align="center" type="index" width="80" >
          <template v-slot="{ $index }">
            <span>{{($index+1)+ (queryParams.pageNo-1)*queryParams.pageSize }}</span>
          </template>
        </el-table-column>
        <el-table-column label="检测报告模板名称" align="center" prop="templateName" />
        <el-table-column label="所属商户名称" align="center" prop="belongBusinessName" />
        <el-table-column label="创建时间" align="center" prop="createTime" >
          <template v-slot="{ row }">
            <span>{{parseTime(row.createTime)}}</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template v-slot="scope">
            <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                       v-hasPermi="['configure:inspection-template:update']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                       v-hasPermi="['configure:inspection-template:delete']">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页组件 -->
      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNo" :limit.sync="queryParams.pageSize"
                  @pagination="getList"/>
    </div>

    <!-- 对话框(添加 / 修改) -->
    <el-dialog :title="title" :visible.sync="open" width="900px" v-dialogDrag append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px" label-position="top">
        <el-row :gutter="50">
          <el-col :span="12">
            <el-form-item label="商户" prop="belongBusinessId">
              <el-select ref="businessName" class="w100" placeholder="请选择" :disabled="isDisable" v-model="form.belongBusinessId" @change="changeBusiness">
                <el-option
                v-for="(item,index) in businessNameList"
                :key="index"
                :label="item.businessName"
                :value="item.id"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="模板名称" prop="templateName">
              <el-input class="w100" v-model="form.templateName" :disabled="isDisable" placeholder="请输入检测报告模板名称" maxlength="64" />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div class="flex-jend">
        <el-select v-model="tempId" placeholder="请先选择商户" class="w160 mr-10">
          <el-option
            v-for="(item,index) in tempList"
            :key="index"
            :label="item.templateName"
            :value="item.id"
          />
        </el-select>
        <el-button :disabled="tempId!==undefined?false:true" @click="importTemplate">导入模板</el-button>
      </div>
      <el-table class="mt20" :data="form.inspectionItems" style="width: 100%">
        <el-table-column
          prop="inspectionItem"
          label="检测项目">
          <template v-slot="{ row }">
            <el-input class="w100" placeholder="请输入" v-model="row.inspectionItem" maxlength="64" ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="inspectionUnit"
          label="单位">
          <template v-slot="{ row }">
            <el-input class="w100" placeholder="请输入" v-model="row.inspectionUnit" maxlength="64" ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          prop="inspectionRequire"
          label="技术要求">
          <template v-slot="{ row }">
            <el-input class="w100" placeholder="请输入" v-model="row.inspectionRequire" maxlength="255" ></el-input>
          </template>
        </el-table-column>
        <el-table-column
          label="操作"
          width="150">
          <template slot-scope="{ row , $index }">
            <el-button type="text" size="small" @click="form.inspectionItems.splice($index,1)">删除</el-button>
          </template>
        </el-table-column>
      </el-table>
      <div class="setting-btn-area" @click="form.inspectionItems.push({})">
        <i style="font-size: 14px;" class="el-icon-plus"></i>
        <div class="buttonText">添加一行数据</div>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { createInspectionTemplate, updateInspectionTemplate, deleteInspectionTemplate, getInspectionTemplate, getInspectionTemplatePage, exportInspectionTemplateExcel , getByBusinessId } from "@/api/configure/inspectionTemplate";
import { getBusinessNameList } from '@/api/basic/businessInfo';
import SearchInfo from "@/components/Customer/SearchForm/index.vue"
import EmptyTable from '@/components/EmptyTable'
export default {
  name: "InspectionTemplate",
  components: {
    SearchInfo,
    EmptyTable
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 检测报告模板列表
      list: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNo: 1,
        pageSize: 10,
        templateName: null,
        templateId: null,
        belongBusinessId: null,
        belongBusinessName: null,
        createTime: [],
      },
      // 搜索工作栏参数
      dataSource: [
        {
          key:'templateName',
          itemType:'input',
          label:'模板名称',
          placeholder:'请输入',
          onEnterKeyUp:this.handleQuery
        },
        {
          key:'belongBusinessId',
          itemType:'select',
          label:'所属商户',
          placeholder:'请选择',
          options: [],
        },
        {
          key: 'createTime',
          itemType: 'datePicker',
          label: '创建时间',
          onEnterKeyUp: this.handleQuery,
        },
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        templateName: [{ required: true, message: "检测报告模板名称不能为空", trigger: "change" }],
        templateId: [{ required: true, message: "模板id不能为空", trigger: "change" }],
        belongBusinessId: [{ required: true, message: "所属商户id不能为空", trigger: "change" }],
        belongBusinessName: [{ required: true, message: "所属商户名称不能为空", trigger: "change" }],
      },
      businessNameList:[],
      tempList: [],
      tempId: undefined,
      isDisable: false,
    };
  },
  created() {
    this.getList();
    this.initDate();
  },
  methods: {
    // 初始化数据
    async initDate(){
      let res = await getBusinessNameList();
      res.data.map(item=>{
        item.label = item.businessName;
        item.value = item.id;
      });
      this.dataSource[1].options = res.data;
      this.businessNameList = res.data;
    },

    /** 查询列表 */
    getList() {
      this.loading = true;
      // 执行查询
      getInspectionTemplatePage(this.queryParams).then(response => {
        this.list = response.data.list;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 取消按钮 */
    cancel() {
      this.open = false;
      this.reset();
    },
    /** 表单重置 */
    reset() {
      this.tempId = undefined;
      this.tempList = [];
      this.form = {
        id: undefined,
        templateName: undefined,
        templateId: undefined,
        belongBusinessId: undefined,
        belongBusinessName: undefined,
        inspectionItems: [],
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNo = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm","searchForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加检测报告模板";
      this.isDisable = false;
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id;
      getInspectionTemplate(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改检测报告模板";
        this.isDisable = true;
        this.getTemplateList(this.form.belongBusinessId);
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (!valid) {
          return;
        }
        let form = JSON.parse(JSON.stringify(this.form));
        if(form.inspectionItems.length == 0){
          this.$message.error("检测项目列表不能为空");
          return false;
        }
        let isNullDate = false;
        form.inspectionItems.map(item=>{
          if(!item.inspectionItem || !item.inspectionRequire || !item.inspectionUnit) isNullDate = true;
        });
        if(isNullDate){
          this.$message.error("检测项目内数据不能为空");
          return false;
        }
        // 修改的提交
        if (form.id != null) {
          updateInspectionTemplate(form).then(response => {
            this.$modal.msgSuccess("修改成功");
            this.open = false;
            this.getList();
          });
          return;
        }
        // 添加的提交
        createInspectionTemplate(form).then(response => {
          this.$modal.msgSuccess("新增成功");
          this.open = false;
          this.getList();
        });
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const id = row.id;
      this.$modal.confirm('是否确认删除检测报告模板编号为"' + id + '"的数据项?').then(function() {
          return deleteInspectionTemplate(id);
        }).then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        }).catch(() => {});
    },
    changeBusiness(e){
      this.$nextTick(async () => {
        let label = this.$refs.businessName.selected.label;
        this.form.belongBusinessName = label;
        this.getTemplateList(e);
      });
    },
    getTemplateList(businessId) {
      getByBusinessId({ businessId }).then(({ data }) => {
        this.tempList = data;
      });
    },
    importTemplate() {
      if (this.tempId === undefined) {
        this.$message.error("请先选择模板");
        return;
      }
      const template = this.tempList.find(item => item.id == this.tempId);
      if (template) {
        this.form.inspectionItems = template.inspectionItems.map(item => {
          return {
            ...item,
            id: undefined,
          }
        });
      }
    },
  }
};
</script>
