<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="区域" prop="region">
        <el-input
          v-model="queryParams.region"
          placeholder="请输入区域"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="单元" prop="unit">
        <el-input
          v-model="queryParams.unit"
          placeholder="请输入单元"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </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="['pssr:aboveall:add']"-->
      <!--        >新增-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <el-col :span="1.5">
        <el-popover
          placement="bottom"
          width="280">
          <div style="text-align: center; margin: 0">
            <el-button type="success" size="mini" @click="handleCreate">通过模板新增</el-button>
            <el-button type="primary" size="mini" @click="handleAdd">直接新增</el-button>
          </div>
          <el-button
            type="primary"
            icon="el-icon-plus"
            size="mini" slot="reference"
            v-hasPermi="['pssr:aboveall:add']"
          >新增
          </el-button>
        </el-popover>
      </el-col>
      <!--<el-col :span="1.5">
        <el-button
          type="success"
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['pssr:aboveall: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="['pssr:aboveall:remove']"
        >删除
        </el-button>
      </el-col>
      <!--<el-col :span="1.5">-->
      <!--<el-button-->
      <!--type="warning"-->
      <!--icon="el-icon-download"-->
      <!--size="mini"-->
      <!--@click="handleExport"-->
      <!--v-hasPermi="['pssr:aboveall:export']"-->
      <!--&gt;导出-->
      <!--</el-button>-->
      <!--</el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="aboveallList" @selection-change="handleSelectionChange" :height="clientHeight"
              border>
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="区域" align="center" prop="region" :show-overflow-tooltip="true"/>
      <el-table-column label="单元" align="center" prop="unit" :show-overflow-tooltip="true"/>
      <el-table-column label="预计开车时间" align="center" prop="drivingTime" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.drivingTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="审批状态" align="center" prop="approveStatus">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.pssr_approve_status" :value="scope.row.approveStatus"
                    :show-type="getTagType(scope.row.approveStatus)"/>
        </template>
      </el-table-column>
      <el-table-column label="确认人" align="center" prop="confirmName" :show-overflow-tooltip="true"/>
      <el-table-column label="确认时间" align="center" prop="confirmationDate">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.confirmationDate, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="备注" align="center" prop="remarks" :show-overflow-tooltip="true"/>
      <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-edit"
                      @click="handleUpdate(scope.row)"
                      v-hasPermi="['pssr:aboveall:edit']"
                    >修改
                    </el-button>-->
          <!--          <el-button-->
          <!--            size="mini"-->
          <!--            type="text"-->
          <!--            icon="el-icon-delete"-->
          <!--            @click="handleDelete(scope.row)"-->
          <!--            v-hasPermi="['pssr:aboveall:remove']"-->
          <!--          >删除-->
          <!--          </el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-tickets"
            @click="gotoSubIndex(scope.row)"
          >检查内容
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleZip(scope.row)"
          >打包
          </el-button>
          <!--<el-button-->
          <!--size="mini"-->
          <!--type="text"-->
          <!--icon="el-icon-download"-->
          <!--@click="handleDownload(scope.row)"-->
          <!--&gt;导出-->
          <!--</el-button>-->
          <el-button
            size="mini"
            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row)"
            v-if="scope.row.approveStatus == '2'"
          >导出
          </el-button>
          <el-button
            type="text"
            size="mini"
            @click="handleExSubcontent(scope.row)"
            v-hasPermi="['pssr:subcontent:export']"
          >预览
          </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"
    />

    <!-- 添加或修改PSSR对话框 -->
    <el-dialog :close-on-click-modal="false" :title="title" :visible.sync="open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="5">
            <el-form-item label="区域" prop="region">
              <el-select v-model="form.region" clearable filterable style="width: 100%;" placeholder="请选择区域"
                         @change="handleKeyChange">
                <el-option
                  v-for="(values, key) in regionGroupOptions"
                  :label="key"
                  :value="key"
                  :key="key"
                />
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="5">
            <el-form-item label="单元" prop="unit">
              <el-select v-model="form.unit" clearable filterable multiple style="width: 100%;" placeholder="请选择单元"
                         :disabled="!form.region">
                <el-option v-for="item in unitOptions"
                           :label="item.unit + '_' + item.remarks"
                           :value="item.unit"
                           :key="item.id "/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="8">
            <el-form-item label="预计开车时间" prop="drivingTime" label-width="140px">
              <el-date-picker clearable
                              v-model="form.drivingTime"
                              type="date"
                              value-format="yyyy-MM-dd"
                              placeholder="选择确认时间">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="6">
            <el-form-item label="是否包含390区域" prop="includePublic" label-width="140px">
              <el-radio v-model="form.includePublic" :label="1">是</el-radio>
              <el-radio v-model="form.includePublic" :label="0">否</el-radio>
            </el-form-item>
          </el-col>
        </el-row>
        <el-card class="mb10">
          <el-table ref="subcontentTable" :data="subcontents" v-loading="subloading" border
                    :row-class-name="tableRowClassName"
                    @selection-change="handleSubSelectionChange" max-height="500">
            <el-table-column label="所属部门" align="center" prop="deptUnit" :show-overflow-tooltip="true" width="80"/>
            <el-table-column label="序号" align="center" prop="serialNumber" :show-overflow-tooltip="true" width="80"/>
            <el-table-column label="项目" align="center" prop="item" :show-overflow-tooltip="true" width="180"/>
            <el-table-column label="开车条件检查内容" align="center" prop="content" :show-overflow-tooltip="true"/>
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="确认人" align="center" prop="confirm" width="180">
              <template slot-scope="scope">
                <el-select v-model="scope.row.confirm" clearable filterable style="width: 100%;"
                           placeholder="请选择确认人" @change="handleChangeConfirm(scope.row.confirm,scope.row)">
                  <el-option v-for="user in userOptions"
                             :label="user.nickName"
                             :value="user.userId"
                             :key="user.userId"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100">
              <template slot-scope="scope">
                <el-tooltip effect="dark" content="添加本项" placement="top">
                  <el-button
                    size="mini"
                    type="text"
                    @click="handleAddRow(scope.row)"
                    :disabled="scope.row.status===1"
                  >✔
                  </el-button>
                </el-tooltip>
                <el-tooltip effect="dark" content="移除本项" placement="top">
                  <el-button
                    size="mini"
                    type="text"
                    @click="handleRemoveRow(scope.row)"
                    :disabled="scope.row.status===0"
                  >✖
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" 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>
        <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>

    <form ref="downloadForm" :action="downloadAction" target="FORMSUBMIT">
      <input name="fileName" v-model="downloadForm.fileName" hidden/>
      <input name="delete" v-model="downloadForm.delete" hidden/>
    </form>

    <el-dialog :close-on-click-modal="false" title="新增PSSR" :visible.sync="model.open" width="80%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="模板" prop="id">
          <el-select v-model="form.id" clearable filterable style="width: 100%;"
                     placeholder="请选择模板生成PSSR数据">
            <el-option
              v-for="item in aboveallList"
              :label="item.region+'_'+item.unit+(item.remarks==null?'':'_'+item.remarks)"
              :value="item.id"
              :key="item.id"
            />
          </el-select>
        </el-form-item>
        <el-card class="mb10">
          <el-table :data="subcontents" v-loading="subloading" border :row-class-name="tableRowClassName"
                    @selection-change="handleSubSelectionChange" max-height="500">
            <el-table-column label="所属部门" align="center" prop="deptUnit" :show-overflow-tooltip="true" width="80"/>
            <el-table-column label="序号" align="center" prop="serialNumber" :show-overflow-tooltip="true" width="80"/>
            <el-table-column label="项目" align="center" prop="item" :show-overflow-tooltip="true" width="180"/>
            <el-table-column label="开车条件检查内容" align="center" prop="content" :show-overflow-tooltip="true"/>
            <el-table-column type="selection" width="55" align="center"/>
            <el-table-column label="确认人" align="center" prop="confirm" width="180">
              <template slot-scope="scope">
                <el-select v-model="scope.row.confirm" clearable filterable style="width: 100%;"
                           placeholder="请选择确认人" @change="handleChangeConfirm(scope.row.confirm,scope.row)">
                  <el-option v-for="user in userOptions"
                             :label="user.nickName"
                             :value="user.userId"
                             :key="user.userId"/>
                </el-select>
              </template>
            </el-table-column>
            <el-table-column label="操作" align="center" width="100">
              <template slot-scope="scope">
                <el-tooltip effect="dark" content="添加本项" placement="top">
                  <el-button
                    size="mini"
                    type="text"
                    @click="handleAddRow(scope.row)"
                    :disabled="scope.row.status===1"
                  >✔
                  </el-button>
                </el-tooltip>
                <el-tooltip effect="dark" content="移除本项" placement="top">
                  <el-button
                    size="mini"
                    type="text"
                    @click="handleRemoveRow(scope.row)"
                    :disabled="scope.row.status===0"
                  >✖
                  </el-button>
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <el-form-item label="备注" prop="remarks">
          <el-input v-model="form.remarks" placeholder="请输入备注"/>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="modelCancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  addAboveall,
  delAboveall,
  exportAboveall,
  genZip,
  getAboveall,
  getPssrUser,
  importTemplate,
  listAboveall
} from "@/api/pssr/aboveall";
import {treeselect} from "@/api/system/dept";
import {getToken} from "@/utils/auth";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import {listPssrModel} from "@/api/pssr/pssrModel";
import {groupList} from "@/api/pssr/region";
import {exportSubcontent, listSubcontent} from "@/api/pssr/subcontent";

export default {
  dicts: ['pssr_approve_status'],
  name: "Aboveall",
  components: {Treeselect},
  data() {
    return {
      downloadForm: {
        fileName: '',
        delete: false,
      },
      downloadAction: process.env.VUE_APP_BASE_API + '/common/download',
      subcontents: [],
      regionGroupOptions: [],
      unitOptions: [],
      userOptions: [],
      // 遮罩层
      loading: true,
      subloading: true,
      // 选中数组
      ids: [],
      subRows: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: false,
      // 总条数
      total: 0,
      // PSSR表格数据
      aboveallList: [],
      // 弹出层标题
      title: "",
      // 部门树选项
      deptOptions: undefined,
      clientHeight: 300,
      // 是否显示弹出层
      open: false,
      model: {
        open: false,
      },
      // 用户导入参数
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的用户数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: {Authorization: "Bearer " + getToken()},
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/pssr/aboveall/importData"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 20,
        approveId: null,
        region: null,
        approveStatus: null,
        unit: null,
        confirm: null,
        confirmationDate: null,
        createrCode: null,
        createdate: null,
        updaterCode: null,
        updatedate: null,
        deptId: null,
        remarks: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        region: [
          {required: true, message: '区域不能为空！', trigger: "blur"}
        ],
        id: [
          {required: true, message: '模板不能为空！', trigger: "blur"}
        ],
        unit: [
          {required: true, message: '单元不能为空！', trigger: "blur"}
        ],
      }
    };
  },
  watch: {
    // 根据名称筛选部门树
    deptName(val) {
      this.$refs.tree.filter(val);
    }
  },
  created() {
    //设置表格高度对应屏幕高度
    this.$nextTick(() => {
      this.clientHeight = document.body.clientHeight - 250
    })
    this.getList();
    this.getTreeselect();
    getPssrUser({}).then(res => {
      this.userOptions = res.data
    });
    groupList({}).then(res => {
      this.regionGroupOptions = res.data;
    });
  },
  methods: {
    handleZip(row) {
      this.queryParams.id = Number(row.id);
      const queryParams = this.queryParams;
      this.$confirm('是否确认打包?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return genZip(queryParams);
      }).then(response => {
        this.msgSuccess("打包成功");
      })
    },
    handleExSubcontent(row) {
      exportSubcontent({
        pageNum: 1,
        pageSize: 50,
        aboveallId: row.id
      }).then(response => {
        window.open(process.env.VUE_APP_BASE_API + response.msg);
      })
    },
    handleDownload(row) {
      let _this = this;
      this.$confirm('是否确认导出?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        _this.downloadForm.fileName = row.zipUrl;
        _this.downloadForm.delete = false;
        _this.$refs['downloadForm'].submit();
      });
    },
    getTagType(val) {
      if (val == 0) {
        return ''
      } else if (val == 1) {
        return 'warning'
      } else if (val == 2) {
        return 'success'
      }
    },
    gotoSubIndex(row) {
      this.$router.push({name: 'Subcontent', params: {aboveallId: row.id}})
    },
    handleChangeConfirm(val, currentRow) {
      // 检查当前行是否在选中行的数组中
      const isSelected = this.subRows.includes(currentRow);

      if (isSelected) {
        // 如果当前行在选中行列表中，批量更新选中的行
        this.subRows.forEach(row => {
          this.$set(row, 'confirm', val);
        });
      } else {
        // 只更新当前行
        this.$set(currentRow, 'confirm', val);
      }
      this.$refs.subcontentTable.clearSelection();
    },
    handleSubSelectionChange(selection) {
      this.subRows = selection
    },
    handleKeyChange() {
      // 根据选中的key更新optionsList
      this.unitOptions = this.regionGroupOptions[this.form.region] || [];
      this.form.unit = ''; // 每次更改key时清空value
    },
    tableRowClassName({row}) {
      if (row.status === 0) {
        return 'row-remove'
      }
      return ''
    },
    handleAddRow(row) {
      row.status = 1
    },
    handleRemoveRow(row) {
      row.status = 0
    },
    /** 查询PSSR列表 */
    getList() {
      this.loading = true;
      listAboveall(this.queryParams).then(response => {
        this.aboveallList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then(response => {
        this.deptOptions = response.data;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 取消按钮
    modelCancel() {
      this.model.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        approveId: null,
        region: null,
        approveStatus: 0,
        includePublic: 0,
        unit: null,
        confirm: null,
        confirmationDate: null,
        delFlag: null,
        createrCode: null,
        createdate: null,
        updaterCode: null,
        updatedate: null,
        deptId: null,
        drivingTime: null,
        remarks: null
      };
      this.subcontents = []
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleCreate() {
      this.reset();
      this.model.open = true;
      this.subloading = true;
      listPssrModel({
        pageNum: 1,
        pageSize: 40
      }).then(res => {
        this.subcontents = res.rows;
        this.subloading = false;
      })
    },
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加PSSR";
      this.subloading = true;
      listPssrModel({
        pageNum: 1,
        pageSize: 200
      }).then(res => {
        this.subcontents = res.rows;
        this.subloading = false;
      })
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      listSubcontent({
        pageNum: 1,
        pageSize: 200,
        aboveallId: id,
      }).then(res => {
        res.rows.forEach(item => {
          item.status = 1;
        })
        this.subcontents = res.rows;
        this.subloading = false;
      })
      getAboveall(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改PSSR";
      });
    },
    /** 提交按钮 */
    submitForm() {
      let flag = false
      this.subcontents.forEach(item => {
        if (item.status === 1 && (item.confirm == null || item.confirm == "")) {
          this.$alert('请确认所有确认人都已选择！', '警告', {
            confirmButtonText: '确定'
          });
          flag = true;
        }
      })
      if (flag)
        return
      if (this.form.unit != null && this.form.unit != "") {
        this.form.unit = this.form.unit.join(",");
      }
      this.form.subcontents = this.subcontents;
      this.$refs["form"].validate(valid => {
        if (valid) {
          addAboveall(this.form).then(response => {
            this.msgSuccess("新增成功");
            this.open = false;
            this.model.open = false;
            this.getList();
          });
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delAboveall(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      })
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有PSSR数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return exportAboveall(queryParams);
      }).then(response => {
        this.download(response.msg);
      })
    },
    /** 导入按钮操作 */
    handleImport() {
      this.upload.title = "用户导入";
      this.upload.open = true;
    },
    /** 下载模板操作 */
    importTemplate() {
      importTemplate().then(response => {
        this.download(response.msg);
      });
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert(response.msg, "导入结果", {dangerouslyUseHTMLString: true});
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    userFormat(userId) {
      for (let item of this.userOptions) {
        if (item.userId == userId) {
          return item.nickName
        }
      }
    },
  }
};
</script>
<style>
/* 定义不同状态对应的颜色 */
.el-table .row-remove,
.el-table .row-remove:hover > td {
  background-color: rgb(251, 112, 112) !important;
}

</style>
