<template>
  <div>
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item prop="startTime">
        <el-date-picker
          v-model="queryParams.startTime"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="开始日期"
          @change="() => queryParams.endTime = ''"
          style="width: 130px"
        />
      </el-form-item>
      <el-form-item>-</el-form-item>
      <el-form-item prop="endTime">
        <el-date-picker
          v-model="queryParams.endTime"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="结束日期"
          :picker-options="{ disabledDate: (t) => t.getTime() < new Date(queryParams.startTime).getTime() - 86400000}"
          style="width: 130px"
        />
      </el-form-item>

      <el-form-item prop="keyWord">
        <el-input
          v-model="queryParams.keyWord"
          placeholder="请输入关键字"
          clearable
          maxlength="50"
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item prop="taskStatus">
        <el-select
          v-model="queryParams.taskStatus"
          placeholder="请选择状态"
          clearable
          filterable
          style="width: 240px"
        >
          <el-option
            v-for="dict in dict.type.repair_task_status"
            v-if="dict.value == 10 || dict.value == 11 || dict.value == 12"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          ></el-option>
        </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="success"
          plain
          icon="el-icon-check"
          size="mini"
          @click="handlePassAll"
          >通过
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-close"
          size="mini"
          @click="handleFailAll"
          >驳回
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleDetailsExport"
        >导出明细
        </el-button>
      </el-col>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table
      v-loading="loading"
      :data="typeList"
      row-key="id"
      ref="multipleTable"
      @selection-change="handleSelectionChange"
      border
      :max-height="650"
    >
      <el-table-column
        type="selection"
        align="center"
        :selectable="selectable"
      />
      <el-table-column align="center" label="序号" type="index" :index="indexContinuation(queryParams.pageNum, queryParams.pageSize)"/>

      <el-table-column label="分公司" align="center" prop="impUnitName" width="140" />
      <el-table-column
        align="center"
        label="退料单位"
        prop="unitName"
      />
      <el-table-column
        label="工程名称"
        align="center"
        prop="projectName"
      />
      <el-table-column
        label="维修审核单号"
        align="center"
        width="150"
        prop="repairNum"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="任务单号"
        align="center"
        width="150"
        prop="repairTaskCode"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="物资类型"
        align="center"
        width="150"
        prop="itemType"
        :show-overflow-tooltip="true"
      />
      <!-- <el-table-column
        label="维修班组"
        align="center"
        prop="teamName"
        width="100px"
        :show-overflow-tooltip="true"
      /> -->
      <el-table-column
        label="提交人"
        align="center"
        prop="createBy"
        width="75px"
        :show-overflow-tooltip="true"
      />
      <el-table-column
        label="提交时间"
        align="center"
        prop="createTime"
        width="100px"
      >
      </el-table-column>

      <el-table-column
        label="状态"
        align="center"
        prop="taskStatus"
        width="120px"
        :show-overflow-tooltip="true"
      >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.repair_task_status"
            :value="scope.row.taskStatus"
          />
        </template>
      </el-table-column>

      <!-- <el-table-column
        label="备注"
        align="center"
        width="100"
        prop="remark"
        :show-overflow-tooltip="true"
      /> -->

      <el-table-column label="操作" align="center" width="100" fixed="right">
        <template slot-scope="scope">
          <el-button
            size="mini"
            style="margin-bottom: 10px"
            type="normal"
            @click="handleView(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"
    />
  </div>
</template>

<script>
import {
  getListTestExamineApply,
} from "@/api/repair/testExamine";
import {
  outerAudit,
} from "@/api/repair/testExamine";
import router from "@/router";
export default {
  name: "Home",
  dicts: ['repair_task_status'],
  data() {
    return {
      // 遮罩层
      loading: true,
      loadingTwo: true,
      updateTime: "",
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      showPeople: false,
      peopleOpen: false,
      // 总条数
      total: 0,
      totalTwo: 0,
      //搜索下拉数据
      typesList: [],
      modelList: [],
      // 字典表格数据
      typeList: [],
      getListPeople: [],
      configUserList: [],
      phoneNumbers: [],
      //选择人员
      chosenUserList: [],
      userList: [],
      // 弹出层标题
      title: "",
      // 日期范围
      dateRange: [],
      statusDataRange: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        time: null, //申请时间
        name: undefined,
        taskStatus: "",
        keyWord: "",
        startTime: "",
        endTime: "",
      },
      form: {
        remark: "",
      },
      // 表单校验
      rules: {
        remark: [
          { required: true, message: "通知内容不能为空", trigger: "blur" },
        ],
      },
      openPrint: false,
      open: false,
      printData: {},
      printTableData: [],
      // 供应商
      supplierStr: "",

      //领料单
      leaseApplyDetails: [],
      // 领料任务详情数据
      leaseApplyData: {},
      passTemp: [],
      faliTemp: [],
    };
  },
  created() {
    const end = new Date()
    let start = new Date()
    start.setMonth(start.getMonth() - 1)
    this.queryParams.startTime = this.format(start)
    this.queryParams.endTime = this.format(end)
    // 不在这里直接调用getList，等字典数据加载完成后再调用
  },
  methods: {
    // 字典数据加载完成后的回调
    onDictReady(dict) {
      // 获取repair_task_status的所有选项，并过滤出有效的选项（值为10、11、12）
      const allOptions = dict.type.repair_task_status || []
      const validOptions = allOptions.filter(item =>
        item.value == 10 || item.value == 11 || item.value == 12
      )

      // 如果有有效选项，设置第一个为默认值
      if (validOptions.length > 0) {
        this.queryParams.taskStatus = validOptions[0].value
      }

      // 执行查询
      this.getList()
    },
    format(date) {
      const y = date.getFullYear()
      const m = String(date.getMonth() + 1).padStart(2, '0')
      const day = String(date.getDate()).padStart(2, '0')
      return `${y}-${m}-${day}`
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.passTemp = [];
      this.failTemp = [];
      this.ids = selection.map((item) => item.taskId);
      selection.forEach((item) => {
        this.passTemp.push({ status: "1",taskId:item.taskId, });
      });
      selection.forEach((item) => {
        this.failTemp.push({  status: "2",taskId:item.taskId, });
      });
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },

    //是否可用勾选框
    selectable(row) {
      if (row.taskStatus == "10" || row.taskStatus == "6") {
        return true;
      } else {
        return false;
      }
    },
    getList() {
      this.loading = true;
      const params = {
        keyWord: this.queryParams.keyWord,
        startTime: this.queryParams.startTime,
        endTime: this.queryParams.endTime,
        pageSize: this.queryParams.pageSize,
        pageNum: this.queryParams.pageNum,
        taskStatus: this.queryParams.taskStatus,
        taskType:5,
      };
      getListTestExamineApply(this.addDateRange(params)).then((response) => {
        this.typeList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      const end = new Date()
      let start = new Date()
      start.setMonth(start.getMonth() - 1)
      this.queryParams.startTime = this.format(start)
      this.queryParams.endTime = this.format(end)
      this.resetForm("queryForm");
      this.queryParams.keyWord = "";
      this.handleQuery();
    },
    /** 通过按钮操作 */
    handlePassAll() {
      if (this.ids.length == 0) {
        this.$alert("请至少勾选一条审核数据", "提示", {
          type: "warning",
          confirmButtonText: "确定",
        });
      } else {
        outerAudit(this.passTemp).then((response) => {
          if (response.code == 200) {
            this.$modal.msgSuccess("通过成功");
            this.$refs.multipleTable.clearSelection();
            this.ids = [];
            this.passTemp = [];
            this.failTemp = [];
            // router.go(0); // 刷新页面
          }
          this.getTaskInfo();
        });
      }
    },
    /** 驳回按钮操作 */
    handleFailAll() {
      if (this.ids.length == 0) {
        this.$alert("请至少勾选一条审核数据", "提示", {
          type: "warning",
          confirmButtonText: "确定",
        });
      } else {
        outerAudit(this.failTemp).then((response) => {
          if (response.code == 200) {
            this.$modal.msgSuccess("驳回成功");
            this.$refs.multipleTable.clearSelection();
            this.ids = [];
            this.passTemp = [];
            this.failTemp = [];
            // router.go(0); // 刷新页面
          }
          this.getTaskInfo();
        });
      }
    },

    /** 查看按钮操作 */
    handleView(row) {
      this.$emit("queryTools", row.taskId, row.id, row);
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.$emit("addTools", row.taskId, row.id,row);
    },

    //----消息通知
    getNowTime() {
      var today = new Date();
      var year = today.getFullYear(); //获取年份
      var month = today.getMonth() + 1; //获取月份
      var day = today.getDate(); //获取日期
      return year + "-" + month + "-" + day;
    },

    // 表单重置
    reset() {
      this.form = {
        taskId: "",
        remark: "",
      };
      this.resetForm("form");
    },

    //获取验收单数据
    getPrintTable(taskId) {
      getAcceptanceForm({ taskId: taskId }).then((response) => {
        this.printData = response.data;
        this.printTableData = response.data.checkDetailsList;

        let supplierList = [];
        this.printTableData.forEach((e) => {
          if (e.supplier) {
            supplierList.push(e.supplier);
          }
        });
        supplierList = [...new Set(supplierList)];

        this.supplierStr = supplierList.join(",");
      });
    },
    //查看验收单
    handlePrint(row) {
      // this.query.taskId = row.taskId
      // this.getPrintTable(row.taskId)
      this.openPrint = true;
      this.title = "机具设备到货验收单";
    },

    //打开领料单
    async handleLld(row) {
      this.open = true;
      var ids = row.id;
      const res = await getApplyInfo(ids);
      console.log(res);
      this.leaseApplyDetails = res.data.leaseApplyDetailsList;
      this.leaseApplyData = res.data.leaseApplyInfo;
      console.log(this.leaseApplyData);
    },

    //打印
    print() {
      this.$refs.remarksPrintRef.print();
    },

    /** 删除按钮操作 */
    handleDeletePurchase(row) {
      // console.log(row)
      let ids = [];
      ids.push(row.id);
      console.log("ids", ids);
      this.$modal
        .confirm("是否确认删除所选择的数据项？")
        .then(function () {
          return applyRemove(ids);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("删除成功");
        })
        .catch(() => {});
    },

    /** 导出按钮操作 */
    handleExport() {
      const formatTime = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}${month}${day}_${hours}${minutes}${seconds}`;
      };

      const currentTime = formatTime(new Date());
      this.download(
        "/material/repair_audit_details/export",
        {
          ...this.queryParams,
          // startTime: this.queryParams.time && this.queryParams.time[0],
          // endTime: this.queryParams.time && this.queryParams.time[1],
        },
        `修试审核_${currentTime}.xlsx`
      );
    },
    handleDetailsExport() {
      const formatTime = (date) => {
        const year = date.getFullYear();
        const month = String(date.getMonth() + 1).padStart(2, '0');
        const day = String(date.getDate()).padStart(2, '0');
        const hours = String(date.getHours()).padStart(2, '0');
        const minutes = String(date.getMinutes()).padStart(2, '0');
        const seconds = String(date.getSeconds()).padStart(2, '0');
        return `${year}${month}${day}_${hours}${minutes}${seconds}`;
      };

      const currentTime = formatTime(new Date());
      this.download(
        "/material/repair/exportAuditDetails",
        {
          ...this.queryParams,
          // startTime: this.queryParams.time && this.queryParams.time[0],
          // endTime: this.queryParams.time && this.queryParams.time[1],
        },
        `修试审核详情_${currentTime}.xlsx`
      );
    },

    //发布按钮
    handleSend(row) {
      const param = { id: row.id, taskId: row.taskId };
      this.$modal
        .confirm("是否确认发布所选择的数据项？")
        .then(function () {
          return applySend(param);
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("发布成功");
        })
        .catch(() => {});
    },

    handleSendAll() {
      if (this.ids.length == 0) {
        this.$alert("请至少勾选一个领料申请", "提示", {
          type: "warning",
          confirmButtonText: "确定",
        });
        return;
      } else {
        applySendAll(this.sendTemp).then((response) => {
          if (response.code == 200) {
            this.$modal.msgSuccess("发布成功");
          }
          this.getList();
        });
      }
    },
  },

  watch: {
    $route: {
      handler(to) {
        if (to.query.keyWord) {
          this.queryParams.keyWord = to.query.keyWord;
        }
      },
      deep: true,
      immediate: true,
    },
  },
};
</script>
<style lang="scss" scoped>
::v-deep.el-table .fixed-width .el-button--mini {
  width: 70px !important;
  margin-bottom: 10px;
}
</style>
