<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="项目编码" prop="fIntersectConstructionId">
        <el-input
          v-model="queryParams.fIntersectConstructionId"
          placeholder="请输入项目编码"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="意外事件标题" prop="fTitle">
        <el-input
          v-model="queryParams.fTitle"
          placeholder="请输入意外事件标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      
      <el-form-item label="上报状态" prop="fUploadType">
        <el-select v-model="queryParams.fUploadType" placeholder="请选择上报状态" clearable size="small">
          <el-option label="未上报" value="0" />
          <el-option label="已上报" value="1" />
        </el-select>
      </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"
          v-if="user.roleId==5"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-if="user.roleId==5"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-if="user.roleId==5"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		     :loading="exportLoading"
          @click="handleExport"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="incList" @selection-change="handleSelectionChange">
      <el-table-column label="项目编码" align="center" prop="projectCode" :show-overflow-tooltip="true"/>
      <el-table-column label="意外事件标题" align="center" prop="fTitle" :show-overflow-tooltip="true"/>
      <el-table-column label="意外事件描述" align="center" prop="fDescription" :show-overflow-tooltip="true"/>
      <el-table-column label="意外事件发生时间" align="center" prop="fOccurrenctTime" :show-overflow-tooltip="true"/>
      <el-table-column label="附件" align="center" prop="fAttachment">
        <template slot-scope="scope">
          <span
            class="dbtn"
            @click="checkFile(scope.row.fAttachment)"
            v-if="scope.row.fAttachment != null && scope.row.fAttachment!=''"
          >
            <i class="el-icon el-icon-view"></i>查看/下载
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="fRemark" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span v-if="scope.row.fRemark">
            {{ scope.row.fRemark }}
          </span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column :label="uploadStateLabel" align="center" prop="uploadState" :formatter="uploadStateFormat" />
      <el-table-column :label="uploadTimeLabel" align="center" prop="uploadTime" :formatter="uploadTimeFormat" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-document"
            @click="handleDetail(scope.row)"
          >详情</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-if="user.roleId==5&&scope.row.entUploadState==0"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-if="user.roleId==5&&scope.row.entUploadState==0"
          >删除</el-button>
          <el-button
            size="mini"
            type="text"
            @click="handleReport(scope.row)"
            v-if="judgeUploadIsShow((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 destroy-on-close :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="140px">
        <el-row class="el-row-table">
          <el-col :span="12">
            <el-form-item label="项目编码" prop="fIntersectConstructionId">
              <el-select
                v-model="form.fIntersectConstructionId"
                placeholder="请输入项目编码"
                style="width: 100%"
              >
                <el-option
                  v-for="item in projectInfo"
                  :key="'' + item.fConGasProInforId"
                  :label="item.fProjectCode"
                  :value="'' +item.fConGasProInforId"
                />
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="意外事件标题" prop="fTitle">
              <el-input v-model="form.fTitle" placeholder="请输入意外事件标题" />
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="意外事件描述" prop="fDescription">
              <el-input type="textarea" v-model="form.fDescription" placeholder="请输入意外事件描述" />
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="意外事件发生时间" prop="fOccurrenctTime">
              <el-date-picker
                style="width: 100%"
                v-model="form.fOccurrenctTime"
                type="datetime"
                value-format="yyyy-MM-dd HH:mm:ss"
                placeholder="意外事件发生事件时间">
              </el-date-picker>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="附件" prop="fAttachment">
              <FileUpload
                listType="picture"
                @resFun="getFileInfo"
                @remove="listRemove"
                :fileArr="fileList"
              />
              <el-input v-show="false" disabled v-model="form.fAttachment"></el-input>
            </el-form-item>
          </el-col>

          <el-col :span="24">
            <el-form-item label="备注" prop="fRemark">
              <el-input v-model="form.fRemark" placeholder="请输入备注" />
            </el-form-item>
          </el-col>

        </el-row>

      </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>

    <!-- 详情 -->
    <DetailInfo ref="detail"/>
  </div>
</template>

<script>
import { listInc, getInc, delInc, addInc, updateInc, exportInc, reportAccidentInfo,entReportConGasProInfo} from "@/api/thirdbuild/accident";
import { conGasProInfoList } from "@/api/thirdbuild/project";
import FileUpload from '@/components/FileUpload';
import{getInfo} from "@/api/login"
let uploadfile = require("@/assets/uploadfile.png");
import { enterpriseLists } from "@/api/regulation/info";
import DetailInfo from "./components/DetailInfo";
export default {
  name: "Inc",
  components: {
    FileUpload,
    DetailInfo
  },
  data() {
    return {
      user:{},
      uploadStateLabel:"",
      uploadTimeLabel:"",
      enterprises: [],
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 涉气第三方施工意外事件表格数据
      incList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fIntersectConstructionId: null,
        fTitle: null,
        fDescription: null,
        fOccurrenctTime: null,
        fAttachment: null,
        fRemark: null,
        fUpdateTime: null,
        fUploadType:null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        fIntersectConstructionId: [
          { required: true, message: "项目编码不能为空", trigger: "blur" }
        ],
        fTitle: [
          { required: true, message: "意外事件标题不能为空", trigger: "blur" }
        ],
        fDescription: [
          { required: true, message: "意外事件描述", trigger: "blur" }
        ],
        fOccurrenctTime: [
          { required: true, message: "意外事件发生事件不能为空", trigger: "blur" }
        ],
        fAttachment: [
          { required: true, message: "附件不能为空", trigger: "blur" }
        ],
      },
      projectInfo: [],
      fileList: []
    };
  },
  created() {
    this.getuserInfo(); 
    this.getEnterpriseLists();
  },
  methods: {
    //所属单位
    getEnterpriseLists(){
      const param = {}; 
        enterpriseLists(param).then(response => { 
          if (response.rows.length>1){ 
            this.enterprises = response.rows;
            this.enterpriseName = response.rows[0].enterpriseName; 
        }else { 
          this.enterprises = response.rows;
          this.enterpriseName = response.rows[0].enterpriseName; 
        }
      }); 
    },
    getuserInfo(){
      getInfo().then(response => {
        this.user = response.user.roles[0]
        this.getList();
        this.getProjectInfo();
      });
    },
    
    //上报状态动态展示
    uploadStateFormat(row, column) { 
      //角色 1 超级管理员  5 企业
      let roleId = this.user.roleId;
      if (roleId == 5) {
        this.uploadStateLabel = "上报状态"
        if (row.entUploadState == '0') {
          return "未上报"
        } else{
          return "已上报"
        } 
      } else { 
        this.uploadStateLabel = "上报省厅状态"
        if (row.govUploadState == '0') {
          return "未上报"
        } else{
          return "已上报"
        } 
      } 
    },
    //上报时间动态展示
    uploadTimeFormat(row, column) {
      //角色 1 超级管理员  5 企业
      let roleId = this.user.roleId;
      if (roleId == 5) {
        this.uploadTimeLabel = "上报时间"
        return row.entUploadTime;
      } else {
        this.uploadTimeLabel = "上报省厅时间"
        return row.govUploadTime;
      }

    },
    /** 查询涉气第三方施工意外事件列表 */
    getList() {
      this.loading = true;
      // 企业查自己的数据
      if (this.user.roleId == 5) {
        this.queryParams.fCompanyInfoId = this.$store.state.user.enterpriseId 
        this.queryParams.entUploadState = this.queryParams.fUploadType;
      }
      // 政府如果按照状态查的话，是查的 govUploadState
      if (this.user.roleId == 3) {
        this.queryParams.govUploadState = this.queryParams.fUploadType;
      } 
      listInc(this.queryParams).then(response => {
        this.incList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    
    //判断 上报是否需要显示，上报分为企业上报 和 政府端上报
    judgeUploadIsShow(row) { 

      //角色 1 超级管理员  5 企业
      let roleId = this.user.roleId;

      // 企业端 上报状态 0-未上报，1-已上报
      let entUploadState = row.entUploadState;

      // 政府端 上报状态 0-未上报，1-已上报
      let govUploadState = row.govUploadState;

      // 如果政府端都已经上报，那就不能显示了。
      if(govUploadState === '1') {
        return false;
      }

      // 如果企业端上报了，则企业端就不能显示了，政府端和 超级管理员能显示
      if(entUploadState === '1' && govUploadState === '0') {
        if (roleId === 5) {
          return false;
        } else {
          return true;
        }
      }

      // 别的情况，都显示
      return true;

    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        fConGasProIncId: null,
        fIntersectConstructionId: null,
        fTitle: null,
        fDescription: null,
        fOccurrenctTime: null,
        fAttachment: null,
        fRemark: null,
        fUpdateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.fConGasProIncId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加涉气第三方施工意外事件";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const fConGasProIncId = row.fConGasProIncId || this.ids
      getInc(fConGasProIncId).then(response => {
        this.form = response.data;
        if (this.form.fAttachment) {

          this.fileList = [{name: '附件', url: uploadfile}];
        } 
        this.open = true;
        this.title = "修改涉气第三方施工意外事件";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.fConGasProIncId != null) {
            updateInc(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.fCompanyInfoId=this.enterprises[0].enterpriseId;
            addInc(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const fConGasProIncIds = row.fConGasProIncId || this.ids;
      this.$confirm('是否确认删除涉气第三方施工意外事件编号为"' + fConGasProIncIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delInc(fConGasProIncIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有涉气第三方施工意外事件数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          
          // 企业查自己的数据
          if (this.user.roleId == 5) {
            this.queryParams.fCompanyInfoId = this.$store.state.user.enterpriseId 
            this.queryParams.entUploadState = this.queryParams.fUploadType;
          }
          // 政府如果按照状态查的话，是查的 govUploadState
          if (this.user.roleId == 3) {
            this.queryParams.govUploadState = this.queryParams.fUploadType;
          } 
          return exportInc(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    //获取第三方施工项目信息
    getProjectInfo(){
      // 企业查自己的数据
      let conGasProInfoQueryParams = {};
      if (this.user.roleId == 5) {
        conGasProInfoQueryParams.fCompanyInfoId= this.$store.state.user.enterpriseId 
      } 
      conGasProInfoList(conGasProInfoQueryParams).then(res =>{
        if(res.code == 200 && res.data){
          this.projectInfo = res.data;
        }
      })
    },
    //上报
    getFileInfo(res){  
      this.form.fAttachment = res.url;
      this.fileList.push({
        name: res.fileName,
        url: uploadfile,
      });
    },
    listRemove(e) {
      this.form.fAttachment = "";
      this.fileList = [];
    },
    checkFile(url) {
      window.open(url,'_blank');
    },
    //详情
    handleDetail(row){
      this.$refs.detail.getDetailInfo(row.fConGasProIncId);
    },
    /** 上报按钮操作 */
    handleReport(row) { 

      // 如果是 超级管理员 或这企业，并且 企业端上报状态为0
      if ((this.user.roleId == 5 || this.user.roleId == 1) && row.entUploadState == '0') {
        this.$confirm('是否确认上报项目编号为"' + row.projectCode + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return entReportConGasProInfo({fConGasProIncId : row.fConGasProIncId});
        }).then(() => {
          this.getList();
        this.msgSuccess("上报成功");
        }).catch(() => {});
      } 
      
      // 如果是 超级管理员 或这政府，并且 政府端上报状态为0
      if ((this.user.roleId == 3 || this.user.roleId == 1) && row.govUploadState == '0') {
        this.$confirm('是否确认上报项目编号为"' + row.projectCode + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return reportAccidentInfo({fConGasProIncId : row.fConGasProIncId});
        }).then(() => {
          this.getList();
        this.msgSuccess("上报成功");
        }).catch(() => {});
      }
    },
  }
};
</script>
<style scoped lang="scss">
  .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>
