<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="证照名称" prop="certificateName">
        <el-input
          v-model="queryParams.certificateName"
          placeholder="请输入证照名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="证照类型" prop="certificateType">
        <el-select v-model="queryParams.certificateType" placeholder="请选择证照类型" clearable size="small">
          <el-option
            v-for = "dict in typeOptions"
            :key = "dict.dictValue"
            :label = "dict.dictLabel"
            :value = "dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="创建时间">
        <el-date-picker
          v-model="dateRange"
          size="small"
          style="width: 240px"
          value-format="yyyy-MM-dd"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" 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"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="enterpriseCertificateList">
      <el-table-column label="证照名称" align="center" prop="certificateName" width="260px" />
      <el-table-column label="证照类型" align="center" prop="certificateType" :formatter="typeFormat" />
      <!--<el-table-column label="证照附件" align="center" prop="certificateUrl">
        <template slot-scope="scope">
          <span
            class="dbtn"
            @click="checkFile(scope.row.certificateUrl)"
            v-if="scope.row.certificateUrl != null && scope.row.certificateUrl!=''"
          >
            <i class="el-icon el-icon-view"></i>点击查看
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>-->
      <el-table-column label="证照附件" align="center" prop="certificateUrl" style="text-align:center;">
        <template slot-scope="scope">
          <img :src="scope.row.certificateUrl" style="width: 20%;vertical-align:middle;cursor:pointer;" @click="showPicture(scope.row)"/>
          <el-image :ref="'a'+scope.row.id" :src="scope.row.certificateUrl" v-show="false" :preview-src-list="[scope.row.certificateUrl]" v-if="scope.row.certificateUrl != '' && scope.row.certificateUrl != null"></el-image>
        </template>
      </el-table-column>
      <el-table-column label="有效日期" align="center" width="200">
        <template slot-scope="scope">
          <span v-if="scope.row.effectiveDate != null && scope.row.effectiveDate != '' && getDays(scope.row.effectiveDate, new Date())<30" style="color: red;">
            {{ scope.row.effectiveDate }}(即将到期)
          </span>
          <span v-if="scope.row.effectiveDate != null && scope.row.effectiveDate != '' && getDays(scope.row.effectiveDate, new Date())>30">
            {{ scope.row.effectiveDate }}
          </span>
          <span v-if="scope.row.effectiveDate == null || scope.row.effectiveDate == ''">-</span>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            v-if="scope.row.status == '0'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
          >修改</el-button>
          <el-button
            v-if="scope.row.status == '0'"
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleLogoff(scope.row)"
          >注销</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

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

    <!-- 添加或修改企业资质证照管理对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row>
          <el-col :span="11">
            <el-form-item label="证照名称" prop="certificateName">
              <el-input v-model="form.certificateName" placeholder="请输入证照名称" />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="证照类型" prop="certificateType">
              <el-select v-model="form.certificateType" placeholder="请选择证照类型" style="width: 100%">
                <el-option v-for="dict in typeOptions"
                           :key="dict.dictValue"
                           :label="dict.dictLabel"
                           :value="dict.dictValue"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="23">
            <el-form-item label="证照附件" prop="certificateUrl">
              <MyFileUpload
                listType="picture-card"
                @resFun="getFileInfo"
                @remove="listRemove"
                :fileArr="fileList"
              />
              <el-input v-show="false" disabled v-model="form.certificateUrl"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="有效日期" prop="effectiveDate">
          <el-date-picker clearable size="small"
            v-model="form.effectiveDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择有效日期">
          </el-date-picker>
        </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>
  </div>
</template>

<script>
import { listEnterpriseCertificate, getEnterpriseCertificate, delEnterpriseCertificate, addEnterpriseCertificate, updateEnterpriseCertificate, exportEnterpriseCertificate } from "@/api/safetyManagement/enterpriseCertificate";
import MyFileUpload from '@/components/MyFileUpload';

export default {
  name: "EnterpriseCertificate",
  components: {
    MyFileUpload
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 企业资质证照管理表格数据
      enterpriseCertificateList: [],
      // 日期范围
      dateRange: [],
      // 上传文件列表
      fileList: [],
      statusOptions: [],
      typeOptions: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        enterpriseId: null,
        certificateName: null,
        certificateType: null,
        certificateUrl: null,
        effectiveDate: null,
        status: null,
        isDel: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        certificateName: [
          { required: true, message: "请输入证照名称", trigger: "blur" }
        ],
        certificateUrl: [
          { required: true, message: "请上传证照附件", trigger: "blur" }
        ],
        effectiveDate: [
          { required: true, message: "请选择证照有效日期", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
    this.getDicts("t_certificate_status").then(response =>{
      this.statusOptions = response.data;
    })
    this.getDicts("t_certificate_type").then(response =>{
      this.typeOptions = response.data;
    })
  },
  methods: {
    // 状态
    statusFormat(row, column) {
      return this.selectDictLabel(this.statusOptions, row.status);
    },
    // 类型
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.certificateType);
    },
    /** 查询企业资质证照管理列表 */
    getList() {
      this.loading = true;
      listEnterpriseCertificate(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.enterpriseCertificateList = response.rows;
        console.log(this.enterpriseCertificateList)
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        enterpriseId: null,
        certificateName: null,
        certificateUrl: null,
        effectiveDate: null,
        status: null,
        isDel: null,
        createTime: null,
        updateTime: null
      };
      this.resetForm("form");
      this.fileList = [];
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加企业资质证照";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getEnterpriseCertificate(id).then(response => {
        this.form = response.data;
        if (this.form.certificateUrl) {
          this.fileList.push({
            url: this.form.certificateUrl,
          });
        }
        this.open = true;
        this.title = "修改企业资质证照";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateEnterpriseCertificate(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addEnterpriseCertificate(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 注销按钮操作 */
    handleLogoff(row) {
      this.$confirm('是否确认注销"' + row.certificateName + '"的证照信息?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        row.status = '1';
        return updateEnterpriseCertificate(row);
      }).then(() => {
        this.getList();
        this.msgSuccess("已注销");
      }).catch(() => {});
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      this.$confirm('是否确认删除"' + row.certificateName + '"的证照信息?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          row.isDel = '1';
          return updateEnterpriseCertificate(row);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    getFileInfo(res){
      this.form.certificateUrl = res.url;
    },
    listRemove(e) {
      this.form.certificateUrl = "";
      this.fileList = [];
    },
    checkFile(url) {
      window.open(url,'_blank');
    },
    getDays(date1 , date2){
      var time = new Date(date1).getTime() - date2.getTime();
      var days = parseInt(time/1000/60/60/24);

      return days;
    },
    showPicture(row){
      this.$refs['a'+row.id].showViewer = true;
      console.log("===",row.id);
    },
  }
};
</script>
<style>
  .dbtn {
    display: inline-block;
    line-height: normal;
    padding-left: 2px;
    padding-right: 2px;
    cursor: pointer;
    border-radius: 3px;
    border-style: solid;
    border-width: 0;
    color: rgb(48, 180, 107);
  }
</style>
