<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="评估年度" prop="saiYear">
        <el-date-picker size="small" style="width: 200px"
          v-model="queryParams.saiYear"
          type="year"
          value-format="yyyy"
          placeholder="选择评估年度"
          @change="handleQuery">
        </el-date-picker>
      </el-form-item>
      <el-form-item :label="$t('数据来源')" prop="source">
        <el-select v-model="queryParams.source" :placeholder="$t('请选择') + $t('数据来源')">
          <el-option key="CTS" label="CTS" value="CTS"></el-option>
          <el-option key="装置" label="装置" value="装置"></el-option>
          <el-option key="督导" label="督导" value="督导"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="cyan" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['production:sai:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['production:sai:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['production:sai:remove']"
        >删除</el-button>
      </el-col>
        <el-col :span="1.5">
            <el-button
                    type="info"
                    icon="el-icon-upload2"
                    size="mini"
                    @click="handleImport"
                    v-hasPermi="['production:sai:edit']"
            >导入</el-button>
        </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          v-hasPermi="['production:sai:export']"
        >导出</el-button>
      </el-col>
	  <right-toolbar :showSearch.sync="showSearch" @queryTable="getListByYear()"></right-toolbar>
    </el-row>

    <el-row class="colorMark">
      <span style="float: left; text-align: left; margin-right: 25px;">
        装置自查人均扣分：<u>{{score}}</u>
      </span>
      <span style="float: left; text-align: left;">
        CTS扣分 / 装置人均扣分：<u>{{score2}}</u>
      </span>
    </el-row>

    <el-table v-loading="loading" :data="saiList" @selection-change="handleSelectionChange" :height="clientHeight" border>
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="检查的装置/设施" align="center" prop="plantName" :show-overflow-tooltip="true"/>
      <el-table-column label="检查日期/时间" align="center" prop="inspectionDate" width="100">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.inspectionDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="识别出的安全问题" align="center" prop="dificiency" :show-overflow-tooltip="true"/>
      <el-table-column label="SAI级别" align="center" prop="saiLevel" :show-overflow-tooltip="true"/>
      <el-table-column label="SAI类别" align="center" prop="category" :show-overflow-tooltip="true" :formatter="saiCategoryFormat"/>
      <el-table-column label="采取或要采取的措施" align="center" prop="actions" :show-overflow-tooltip="true"/>
      <el-table-column label="用户" align="center" prop="userDeptName" :show-overflow-tooltip="true"/>
      <el-table-column label="数据来源" align="center" prop="source" :show-overflow-tooltip="true"/>
      <el-table-column label="检查人" align="center" prop="applicantName" :show-overflow-tooltip="true"/>
      <el-table-column label="操作" align="center" fixed="right" width="120" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['production:sai:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['production:sai:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getListByYear"
    />

    <!-- 添加或修改SAI信息对话框 -->
    <el-dialog  :close-on-click-modal="false" :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="检查的装置/设施" prop="plantId">
          <treeselect v-model="form.plantId" :options="deptOptions" :show-count="true" placeholder="请选择检查的装置/设施" />
        </el-form-item>
        <el-form-item label="检查日期/时间" prop="inspectionDate">
          <el-date-picker clearable size="small" style="width: 200px"
            v-model="form.inspectionDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择检查日期/时间">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="识别出的安全问题" prop="dificiency">
          <el-input v-model="form.dificiency" placeholder="请输入识别出的安全问题" />
        </el-form-item>
        <el-form-item label="SAI级别" prop="saiLevel">
          <el-select v-model="form.saiLevel" placeholder="请选择SAI级别" @change="handleSaiLevelChange">
            <el-option key="1" label="1" value="1"></el-option>
            <el-option key="2" label="2" value="2"></el-option>
            <el-option key="3" label="3" value="3"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('SAI类别')" prop="category">
          <el-select
            @change="handleSaiCategoryChange"
            filterable
            clearable
            v-model="form.category"
            placeholder="请选择SAI类别">
            <el-option
              v-for="dict in saiCategoryOptions2"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="采取或要采取的措施" prop="actions">
          <el-input v-model="form.actions" placeholder="请输入采取或要采取的措施" />
        </el-form-item>
        <el-form-item label="用户" prop="userDept">
          <treeselect v-model="form.userDept" :options="deptOptions" :show-count="true" placeholder="请选择用户" />
        </el-form-item>
        <el-form-item :label="$t('数据来源')" prop="source">
          <el-select v-model="form.source" :placeholder="$t('请选择') + $t('数据来源')">
            <el-option key="CTS" label="CTS" value="CTS"></el-option>
            <el-option key="装置" label="装置" value="装置"></el-option>
            <el-option key="督导" label="督导" value="督导"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item :label="$t('检查人')" prop="applicant">
          <el-select
            filterable
            clearable
            v-model="form.applicant"
            placeholder="请选择检查人">
            <el-option
              v-for="dict in applicantOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="归属部门" prop="deptId">
            <treeselect v-model="form.deptId" :options="deptOptions" :show-count="true" placeholder="请选择归属部门" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 用户导入对话框 -->
    <el-dialog  :close-on-click-modal="false" :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body>
          <el-upload
                  ref="upload"
                  :limit="1"
                  accept=".xlsx, .xls"
                  :headers="upload.headers"
                  :action="upload.url + '?updateSupport=' + upload.updateSupport"
                  :disabled="upload.isUploading"
                  :on-progress="handleFileUploadProgress"
                  :on-success="handleFileSuccess"
                  :auto-upload="false"
                  drag
          >
              <i class="el-icon-upload"></i>
              <div class="el-upload__text">
                  将文件拖到此处，或
                  <em>点击上传</em>
              </div>
              <div class="el-upload__tip" slot="tip">
                  <!--<el-checkbox v-model="upload.updateSupport" />是否更新已经存在的用户数据-->
                  <el-link type="info" style="font-size:12px" @click="importTemplate">下载模板</el-link>
              </div>
              <form ref="downloadFileForm" :action="upload.downloadAction" target="FORMSUBMIT">
                <input name="type" :value="upload.type" hidden />
              </form>
              <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入“xls”或“xlsx”格式文件！</div>
          </el-upload>
          <div slot="footer" class="dialog-footer">
              <el-button type="primary" @click="submitFileForm">确 定</el-button>
              <el-button @click="upload.open = false">取 消</el-button>
          </div>
      </el-dialog>
  </div>
</template>

<script>
import { calcScoreByYear, calcScore2ByYear, listSai, listSaiByYear, getSai, delSai, addSai, updateSai, exportSai, importTemplate} from "@/api/production/sai";
import { treeselect, alltreeselect } from "@/api/system/dept";
import { getToken } from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import { listStaffmgrByDeptAndTeam, getLoginStaffInfo } from "@/api/plant/staffmgr";
import { categoryList } from "@/api/production/category";

export default {
  name: "Sai",
  components: { Treeselect },
  data() {
    return {
      // SAI类别列表
      saiCategoryOptions: [],
      saiCategoryOptions2: [],
      // 登记人列表
      applicantOptions: [],
      score: null,
      score2: null,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // SAI信息表格数据
      saiList: [],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      clientHeight:300,
      // 是否显示弹出层
      open: false,
        // 用户导入参数
        upload: {
            //下载模板请求地址
            downloadAction: process.env.VUE_APP_BASE_API + '/common/template',
            //下载模板类型
            type: 'sai',
            // 是否显示弹出层（用户导入）
            open: false,
            // 弹出层标题（用户导入）
            title: "",
            // 是否禁用上传
            isUploading: false,
            // 是否更新已经存在的用户数据
            updateSupport: 0,
            // 设置上传的请求头部
            headers: { Authorization: "Bearer " + getToken() },
            // 上传的地址
            url: process.env.VUE_APP_BASE_API + "/production/sai/importData"
        },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        saiId: null,
        plantId: null,
        inspectionDate: null,
        dificiency: null,
        saiLevel: null,
        category: null,
        actions: null,
        userDept: null,
        source: null,
        saiYear: null,
        deptId:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        plantId: [
          { required: true, message: this.$t('检查的装置/设施') + this.$t('不能为空'), trigger: "change" }
        ],
        inspectionDate: [
          { required: true, message: this.$t('检查日期/时间') + this.$t('不能为空'), trigger: "change" }
        ],
        dificiency: [
          { required: true, message: this.$t('识别出的安全问题') + this.$t('不能为空'), trigger: "change" }
        ],
        saiLevel: [
          { required: true, message: this.$t('SAI级别') + this.$t('不能为空'), trigger: "change" }
        ],
        category: [
          { required: true, message: this.$t('SAI类别') + this.$t('不能为空'), trigger: "change" }
        ],
        actions: [
          { required: true, message: this.$t('采取或要采取的措施') + this.$t('不能为空'), trigger: "change" }
        ],
        userDept: [
          { required: true, message: this.$t('用户') + this.$t('不能为空'), trigger: "change" }
        ],
        source: [
          { required: true, message: this.$t('数据来源') + this.$t('不能为空'), trigger: "change" }
        ],
        deptId: [
          { required: true, message: this.$t('归属部门') + this.$t('不能为空'), trigger: "change" }
        ],
      }
    };
  },
  watch: {
        // 根据名称筛选部门树
        deptName(val) {
            this.$refs.tree.filter(val);
        }
   },
  created() {
    this.setYear();
      //设置表格高度对应屏幕高度
      this.$nextTick(() => {
          this.clientHeight = document.body.clientHeight -250
      })
    // this.getList();
    this.getListByYear();
    this.calcScoreByYear();
    this.calcScore2ByYear();
    this.getTreeselect();
    this.listStaffmgrByDeptAndTeam(null, null);
    this.getCategoryList();
  },
  methods: {

    // 处理SAI级别下拉框选中事件
    handleSaiLevelChange() {
      this.saiCategoryOptions2 = [];
      let saiLevel = this.form.saiLevel;
      let saiCategoryOptionsTemp = [];
      for (let i = 0; i < this.saiCategoryOptions.length; i++) {
        if (saiLevel == 1 && this.saiCategoryOptions[i].dictLabel.indexOf("-1-") != -1) {
          let saiCategoryOption = {
            dictValue: this.saiCategoryOptions[i].dictValue,
            dictLabel: this.saiCategoryOptions[i].dictLabel,
          };
          saiCategoryOptionsTemp.push(saiCategoryOption);
        }
        if (saiLevel == 2 && this.saiCategoryOptions[i].dictLabel.indexOf("-2-") != -1) {
          let saiCategoryOption = {
            dictValue: this.saiCategoryOptions[i].dictValue,
            dictLabel: this.saiCategoryOptions[i].dictLabel,
          };
          saiCategoryOptionsTemp.push(saiCategoryOption);
        }
        if (saiLevel == 3 && this.saiCategoryOptions[i].dictLabel.indexOf("-3-") != -1) {
          let saiCategoryOption = {
            dictValue: this.saiCategoryOptions[i].dictValue,
            dictLabel: this.saiCategoryOptions[i].dictLabel,
          };
          saiCategoryOptionsTemp.push(saiCategoryOption);
        }
      }
      this.saiCategoryOptions2 = saiCategoryOptionsTemp;
    },
    // 处理SAI类别下拉框选中事件
    handleSaiCategoryChange() {
      for (let i = 0; i < this.saiCategoryOptions.length; i++) {
        if (this.form.category == this.saiCategoryOptions[i].dictValue) {
          if (this.saiCategoryOptions[i].dictLabel.indexOf("-1-") != -1) {
            this.form.saiLevel = 1;
          }
          if (this.saiCategoryOptions[i].dictLabel.indexOf("-2-") != -1) {
            this.form.saiLevel = 2;
          }
          if (this.saiCategoryOptions[i].dictLabel.indexOf("-3-") != -1) {
            this.form.saiLevel = 3;
          }
        }
      }
    },
    // SAI类别字典翻译
    saiCategoryFormat(row, column) {
      return this.selectDictLabel(this.saiCategoryOptions, row.category);
    },
    /** 获取SAI类别列表数据 */
    getCategoryList() {
      categoryList().then(response => {
        let data = response.data;
        for (let i = 0; i < data.length; i++) {
          if (data[i].saiCategoryName != null && data[i].saiCategoryName != "") {
            this.saiCategoryOptions.push({
              dictLabel: data[i].saiCategoryName,
              dictValue: data[i].saiCategoryId
            });
          }
        }
      });
    },
    /** 加载当前登录员工信息 */
    getLoginStaffInfo() {
      getLoginStaffInfo().then(response => {
        let staff = response.data;
        if (staff != null) {
          this.form.applicant = staff.userId;
        }
      });
    },
    /** 加载登记人列表 */
    listStaffmgrByDeptAndTeam(applicantDept, applicantTeam) {
      listStaffmgrByDeptAndTeam({
        deptId: applicantDept,
        team: applicantTeam
      }).then(response => {
        let staffList = response.rows;
        this.applicantOptions = [];
        for (let i = 0; i < staffList.length; i++) {
          let staffOption = {
            dictLabel: staffList[i].staffid + " - " + staffList[i].name,
            dictValue: staffList[i].userId
          }
          this.applicantOptions.push(staffOption);
        }
      });
    },
    /** 计算当年装置自查人均扣分 */
    calcScoreByYear() {
      calcScoreByYear(this.queryParams.saiYear).then(response => {
        this.score = response.msg;
      });
    },
    /** 计算CTS扣分 / 装置人均扣分 */
    calcScore2ByYear() {
      calcScore2ByYear(this.queryParams.saiYear).then(response => {
        this.score2 = response.msg;
      });
    },
    /** 评估年度默认为当年 */
    setYear() {
      this.queryParams.saiYear = new Date().getFullYear().toString();
    },
    /** 查询SAI信息列表 */
    getListByYear() {
      this.loading = true;
      listSaiByYear(this.queryParams).then(response => {
        this.saiList = response.rows;
        this.total = response.total;
        this.loading = false;
        this.calcScoreByYear();
        this.calcScore2ByYear();
      });
    },
    getList() {
      this.loading = true;
      listSai(this.queryParams).then(response => {
        this.saiList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
     /** 查询部门下拉树结构 */
     getTreeselect() {
          alltreeselect().then(response => {
              this.deptOptions = response.data;
          });
     },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        saiId: null,
        plantId: null,
        inspectionDate: null,
        dificiency: null,
        saiLevel: null,
        category: null,
        actions: null,
        userDept: null,
        source: null,
        delFlag: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
        applicant: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getListByYear();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.saiId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getLoginStaffInfo();
      this.open = true;
      this.title = "添加SAI信息";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const saiId = row.saiId || this.ids
      getSai(saiId).then(response => {
        this.saiCategoryOptions2 = this.saiCategoryOptions;
        this.form = response.data;
        this.form.category = Number(this.form.category);
        this.open = true;
        this.title = "修改SAI信息";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.saiId != null) {
            updateSai(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getListByYear();
              this.calcScoreByYear();
              this.calcScore2ByYear();
            });
          } else {
            addSai(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getListByYear();
              this.calcScoreByYear();
              this.calcScore2ByYear();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const saiIds = row.saiId || this.ids;
      this.$confirm('是否确认删除?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delSai(saiIds);
        }).then(() => {
          this.getListByYear();
          this.msgSuccess("删除成功");
        })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有SAI信息数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return exportSai(queryParams);
        }).then(response => {
          this.download(response.msg);
        })
    },
      /** 导入按钮操作 */
      handleImport() {
          this.upload.title = "用户导入";
          this.upload.open = true;
      },
      /** 下载模板操作 */
      importTemplate() {
        this.$refs['downloadFileForm'].submit()
      },
      // 文件下载处理
      handleDownload(row) {
        var name = row.fileName;
        var url = row.fileUrl;
        var suffix = url.substring(url.lastIndexOf("."), url.length);
        const a = document.createElement('a')
        a.setAttribute('download', name)
        a.setAttribute('target', '_blank')
        a.setAttribute('href', process.env.VUE_APP_BASE_API + url)
        a.click()
      },
      // 文件上传中处理
      handleFileUploadProgress(event, file, fileList) {
          this.upload.isUploading = true;
      },
      // 文件上传成功处理
      handleFileSuccess(response, file, fileList) {
        this.upload.open = false;
        this.upload.isUploading = false;
        this.$refs.upload.clearFiles();
        if (response.data[0] != null) {
          this.$alert(this.$t('成功导入') + response.msg + this.$t('条数据') + "，" + this.$t('第') + response.data + this.$t('行数据出现错误导入失败')+"。", this.$t('导入结果'), { dangerouslyUseHTMLString: true });
        }else {
          this.$alert(this.$t('成功导入') + response.msg + this.$t('条数据'), this.$t('导入结果'), { dangerouslyUseHTMLString: true });
        }
        this.getListByYear();
      },
      // 提交上传文件
      submitFileForm() {
          this.$refs.upload.submit();
      }
  }
};
</script>

<style>
  .colorMark {
    color: #6f6f6f;
    text-align: right;
    font-weight:bold;
    font-size: 13px;
    padding-bottom: 10px;
  }
  .rectangleLightgreen {
    width: 40px !important;
    height: 20px !important;
  }
  .rectangleFlesh {
    width: 40px !important;
    height: 20px !important;
  }
  .rectangleYellow {
    width: 40px !important;
    height: 20px !important;
  }
  .rectangleRed {
    width: 40px !important;
    height: 20px !important;
  }
  .rectangleGreen {
    width: 40px !important;
    height: 20px !important;
  }
</style>
