<template>
  <div>
    <div style="text-align: right; margin-bottom: 10px" v-if="keyType != 'SV'">
      <el-button
        type="primary"
        icon="el-icon-plus"
        size="mini"
        @click="handleAdd"
        v-hasPermi="['warn:rectification:add']"
        >添加问题</el-button
      >
    </div>

    <el-table v-loading="loading" border :data="rectificationList">
      <el-table-column
        label="序号"
        type="index"
        width="50"
        align="center"
        fixed
      />
      <!-- <el-table-column
        label="监管id"
        align="center"
        prop="inspectionId"
        min-width="120"
      /> -->
      <el-table-column
        label="责任单位"
        align="center"
        prop="responsibleUnit"
        :formatter="unitFormat"
        min-width="120"
      />
      <el-table-column
        label="单位类型"
        align="center"
        prop="responsibleUnitType"
        :formatter="unitTypeFormat"
        min-width="120"
      />

      <el-table-column
        label="检查时间"
        align="center"
        prop="noticeBegainTime"
        min-width="120"
      >
        <template slot-scope="scope">
          <span>{{
            parseTime(scope.row.noticeBegainTime, "{y}-{m}-{d}")
          }}</span>
        </template>
      </el-table-column>
      <el-table-column
        label="问题描述"
        align="center"
        prop="context"
        min-width="120"
      />

      <el-table-column
        label="处理状态"
        align="center"
        prop="isFinish"
        :formatter="isFinishFormat"
        min-width="120"
      />

      <!-- <el-table-column
        label="整改时间"
        align="center"
        prop="feedbackTime"
        min-width="120"
      >
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.feedbackTime, "{y}-{m}-{d}") }}</span>
        </template>
      </el-table-column> -->
      <el-table-column
        label="整改反馈"
        align="center"
        prop="feedback"
        min-width="120"
      />

      <!-- <el-table-column
        label="责任单位"
        align="center"
        prop="unitArray"
        :formatter="unitArrayFormat"
        min-width="120"
      />
      <el-table-column
        label="整改完成情况"
        align="center"
        prop="isFinish"
        :formatter="isFinishFormat"
        min-width="120"
      /> -->
      <!-- <el-table-column
        label="整改相关附件"
        align="center"
        prop="ccc"
        min-width="120"
      /> -->
      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
        width="180"
        fixed="right"
      >
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row, scope.$index)"
            v-hasPermi="['warn:rectification:edit']"
            >整改</el-button
          >
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row, scope.$index)"
            v-hasPermi="['warn:rectification: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="getList"
    />

    <!-- 添加或修改整改通知书对话框 -->
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="1200px"
      append-to-body
      :close-on-click-modal="false"
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <!-- <el-form-item label="监管id" prop="inspectionId">
          <el-input v-model="form.inspectionId" placeholder="请输入监管id" />
        </el-form-item> -->
        <!-- <el-form-item label="发文单位" prop="issuingUnit">
          <el-input v-model="form.issuingUnit" placeholder="请输入发文单位" />
        </el-form-item>
        <el-form-item label="文号" prop="documentNumber">
          <el-input v-model="form.documentNumber" placeholder="请输入文号" />
        </el-form-item> -->

        <el-form-item label="责任单位" prop="responsibleUnit">
          <el-select
            v-model="form.responsibleUnit"
            placeholder="请选择责任单位"
            filterable
            clearable
            size="small"
            style="width: 100%"
          >
            <el-option
              v-for="dict in unitOptions"
              :key="dict.id + dict.enterpriseName"
              :label="dict.enterpriseName"
              :value="dict.id"
              @click.native="getType(dict)"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="单位类型" prop="responsibleUnitType">
          <el-select
            v-model="form.responsibleUnitType"
            placeholder="请选择单位类型"
            filterable
            clearable
            size="small"
            style="width: 100%"
            disabled
          >
            <el-option
              v-for="dict in unitTypeOptions"
              :key="dict.value + dict.name"
              :label="dict.name"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="检查时间" prop="noticeBegainTime">
          <el-date-picker
            clearable
            size="small"
            style="width: 100%"
            v-model="form.noticeBegainTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择检查时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="问题描述" prop="context">
          <el-input
            v-model="form.context"
            placeholder="请输入问题描述"
            type="textarea"
          />
        </el-form-item>

        <el-form-item label="整改时间" prop="feedbackTime" v-if="!isAdd">
          <el-date-picker
            clearable
            size="small"
            style="width: 100%"
            v-model="form.feedbackTime"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择整改时间"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="整改反馈" prop="feedback" v-if="!isAdd">
          <el-input
            v-model="form.feedback"
            placeholder="请输入整改反馈"
            type="textarea"
          />
        </el-form-item>

        <!-- <el-form-item label="整改通知书" prop="rectificationAttachment">
          <el-upload
            class="upload-demo"
            action="thinking/common/upload"
            :headers="headers"
            :before-upload="(file) => $fileBeforeUpload(file, 'fileList1')"
            :on-preview="handlePreview"
            :on-remove="(file) => handleOpinionRemove(file, 'fileList1')"
            :before-remove="beforeRemove"
            multiple
            :on-exceed="handleExceed"
            :on-success="
              (_, fileList) => submitOpinionUpload(fileList, 'fileList1')
            "
            :file-list="fileList1"
          >
            <el-button size="small" type="primary" plain>
              <i class="el-icon-upload el-icon--right"></i>
              点击上传
            </el-button>
            <div slot="tip" class="el-upload__tip">
              支持jpg/png/pdf/word/excel文件等，不超过200M
            </div>
          </el-upload>
        </el-form-item> -->
      </el-form>
      <!-- <responsibleUnit
        v-if="open && form.id"
        :isAdd="isAdd"
        :inspectionId="inspectionId"
        :rectificationId="form.id"
        :proNo="proNo"
        :proCode="proCode"
      /> -->
      <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 {
  listRectification,
  getRectification,
  delRectification,
  addRectification,
  updateRectification,
  exportRectification,
} from "@/api/warn/rectification";
import { listInfo } from "@/api/build/enteInfo";
import { getToken } from "@/utils/auth";
import { getFileStream } from "@/api/system/upload";
import responsibleUnit from "./responsibleUnit.vue";

export default {
  name: "Rectification",
  props: ["inspectionId", "proNo", "proCode", "keyType"],
  components: {
    responsibleUnit,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 整改通知书表格数据
      rectificationList: [],
      // 变化的list
      changeList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        ids: null,
        data: {
          inspectionId: null,
          issuingUnit: null,
          documentNumber: null,
          noticeBegainTime: null,
          rectificationAttachment: null,
          createUid: null,
          updateUid: null,
          owerDept: null,
        },
        // 排序方式
        params: {
          // 按哪个字段排序
          orderBy: "create_time",
          // desc降序，升序asc
          sortBy: "desc",
        },
      },
      // 查询参数
      unitParams: {
        pageNum: 1,
        pageSize: 10,
        ids: null,
        data: {
          proCode: null,
          proNo: null,
        },
        // 排序方式
        params: {
          // 按哪个字段排序
          orderBy: "create_time",
          // desc降序，升序asc
          sort: "desc",
        },
      },
      unitOptions: [],
      unitTypeOptions: [
        {
          name: "设计单位",
          value: "0",
        },
        {
          name: "施工单位",
          value: "1",
        },
        {
          name: "监理单位",
          value: "2",
        },
        {
          name: "其他单位",
          value: "3",
        },
      ],
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        responsibleUnit: [
          { required: true, message: "请选择责任单位", trigger: "blur" },
        ],
        content: [
          { required: true, message: "请输入发文单位", trigger: "blur" },
          { max: 250, message: "字符长度最大为250", trigger: "blur" },
        ],
      },
      // 请求头
      headers: {
        jianwei: "jwtech " + getToken(),
      },
      fileList1: [],
      isAdd: false,
      // 当前编辑的数据
      nowIndex: 0,
    };
  },
  created() {
    if (this.inspectionId) {
      this.getList();
    } else {
      this.loading = false;
    }
    this.getUnit();
    this.getDicts("rectification_completion").then((response) => {
      this.isFinishOptions = response.data;
    });
  },
  methods: {
    getType(dict) {
      this.form.responsibleUnitType = dict.enterpriseType;
      console.log(111, this.form.responsibleUnitType);
    },
    /** 查询整改通知书列表 */
    getList() {
      this.loading = true;
      this.queryParams.data.inspectionId = this.inspectionId;
      listRectification(this.queryParams).then((response) => {
        this.rectificationList = response.records;
        console.log("this.rectificationList", this.rectificationList);
        this.total = response.total;
        this.loading = false;
      });
    },
    getUnit() {
      this.unitParams.data.proNo = this.proNo;
      this.unitParams.data.proCode = this.proCode;
      listInfo(this.unitParams).then((response) => {
        this.unitOptions = response.data.enterpriseInfoList;
        // console.log(88888888888, this.unitOptions);
      });
    },
    unitFormat(row) {
      let res = "";
      this.unitOptions.filter((item) => {
        if (item.id == row.responsibleUnit) {
          res = item.enterpriseName;
          return res;
        }
      });
    },
    unitTypeFormat(row) {
      let res = "";
      this.unitTypeOptions.filter((item) => {
        if (item.value == row.responsibleUnitType) {
          res = item.label;
          return res;
        }
      });
    },
    unitArrayFormat(row) {
      let res = "";
      row.unitArray?.forEach((item) => {
        // this.unitOptions.forEach((sub) => {
        //   if (item === sub.enterpriseName) {
        res = res + item + "、";
        // }
        // });
      });
      return res;
    },
    isFinishFormat(row) {
      return this.selectDictLabel(this.isFinishOptions, row.isFinish);
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.fileList1 = [];
      this.form = {
        id: null,
        responsibleUnit: null,
        responsibleUnitType: null,
        context: null,
        noticeBegainTime: null,
        feedbackTime: null,
        feedback: null,
        inspectionId: null,
        issuingUnit: null,
        documentNumber: null,
        noticeBegainTime: null,
        rectificationAttachment: null,
        createTime: null,
        createUid: null,
        updateUid: null,
        updateTime: null,
        owerDept: null,
        remark: null,
      };
      this.resetForm("form");
    },
    // 查询表单重置
    resetQueryForm() {
      this.queryParams = {
        pageNum: 1,
        pageSize: 10,
        data: {
          id: null,
          responsibleUnit: null,
          responsibleUnitType: null,
          context: null,
          noticeBegainTime: null,
          feedbackTime: null,
          feedback: null,
          inspectionId: null,
          issuingUnit: null,
          documentNumber: null,
          noticeBegainTime: null,
          rectificationAttachment: null,
          createTime: null,
          createUid: null,
          updateUid: null,
          updateTime: null,
          owerDept: null,
          remark: null,
        },
        // 排序方式
        params: {
          // 按哪个字段排序
          orderBy: "create_time",
          // desc降序，升序asc
          sortBy: "desc",
        },
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetQueryForm();
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.isAdd = true;
      this.open = true;
      this.title = "添加整改通知书";
    },
    /** 修改按钮操作 */
    handleUpdate(row, index) {
      this.reset();
      this.isAdd = false;
      this.nowIndex = index;
      this.form = { ...row };
      if (this.form.rectificationAttachment) {
        this.fileList1 = JSON.parse(this.form.rectificationAttachment);
      }
      this.open = true;
      this.title = "修改整改通知书";
      // const id = row.id || this.ids;
      // getRectification(id).then((response) => {
      //   this.form = response.data;
      //   if (this.form.rectificationAttachment) {
      //     this.fileList1 = JSON.parse(this.form.rectificationAttachment);
      //   }
      //   this.open = true;
      //   this.title = "修改整改通知书";
      // });
    },
    /** 提交按钮 */
    submitForm() {
      this.form.rectificationAttachment =
        this.fileList1.length > 0 ? JSON.stringify(this.fileList1) : null;
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.keyType == "SA" || this.keyType == "SV") {
            if (this.form.id != null) {
              updateRectification(this.form).then((response) => {
                if (response.code === 200) {
                  this.msgSuccess("修改成功");
                  this.open = false;
                  this.getList();
                }
              });
            } else {
              this.form.inspectionId = this.inspectionId;
              addRectification(this.form).then((response) => {
                if (response.code === 200) {
                  this.msgSuccess("新增成功");
                  this.open = false;
                  this.getList();
                }
              });
            }
          } else {
            if (this.isAdd) {
              let form = { ...this.form };
              this.$set(
                this.rectificationList,
                this.rectificationList.length,
                form
              );
              this.open = false;
            } else {
              let form = { ...this.form };
              this.$set(this.rectificationList, this.nowIndex, form);
              this.open = false;
            }
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row, index) {
      if (this.keyType == "SA" || this.keyType == "SV") {
        const ids = row.id || this.ids;
        if (ids) {
          this.$confirm("是否删除选中的数据？", "警告", {
            confirmButtonText: "确定",
            cancelButtonText: "取消",
            type: "warning",
          })
            .then(function () {
              return delRectification(ids);
            })
            .then(() => {
              this.getList();
              this.msgSuccess("删除成功");
            })
            .catch(function () {});
        } else {
          this.$message.warning("请选择要删除的数据！！");
        }
      } else {
        this.nowIndex = index;
        this.$confirm("是否删除选中的数据？", "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        })
          .then(() => {
            this.rectificationList.splice(this.nowIndex);
          })
          .then(() => {
            this.msgSuccess("删除成功");
          })
          .catch(function () {});
      }
    },
    // 上传意见附件
    submitOpinionUpload(fileList, name) {
      console.log(name, fileList);
      this[name].push({
        name: fileList.name,
        fileName: fileList.response.fileName,
        url: fileList.response.url,
        uid: fileList.uid,
      });
      console.log(name, this[name]);
    },
    handleOpinionRemove(file, name) {
      // console.log(file, fileList1);
      let index = this[name].findIndex((item) => item.uid === file.uid);
      // 删除文件
      this[name].splice(index, 1);
    },
    // 表格中下载
    downloadFile(fileList, index) {
      console.log(fileList);
      let file = JSON.parse(fileList)[index];
      this.handlePreview(file);
    },
    // 点击预览的文件进行下载
    handlePreview(file) {
      // console.log(file);
      getFileStream({ fileName: file.fileName }).then((res) => {
        const blob = new Blob([res], {
          // type类型后端返回来的数据中会有，根据自己实际进行修改
          // 表格下载为 application/xlsx，压缩包为 application/zip等，
          type: "application/xlsx",
        }); //excel,pdf等
        const href = URL.createObjectURL(blob); //创建新的URL表示指定的blob对象
        const a = document.createElement("a"); //创建a标签
        a.style.display = "none";
        a.href = href; // 指定下载链接
        a.download = file.name; //指定下载文件名
        a.click(); //触发下载
        URL.revokeObjectURL(a.href); //释放URL对象
      });
    },
    handleExceed(files, fileList) {
      this.$message.warning(
        `当前限制选择 3 个文件，本次选择了 ${files.length} 个文件，共选择了 ${
          files.length + fileList.length
        } 个文件`
      );
    },
    beforeRemove(file, fileList) {
      return this.$confirm(`确定移除 ${file.name}？`);
    },
  },
};
</script>
<style lang="scss" scoped>
@import "@/assets/css/dialog.scss";
//::v-deep {
//   .el-dialog {
//       margin-top: 10vh !important;
//    }
//}
</style>
