<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="68px"
    >
      <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_end_task_status"
            :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="warning"
          plain
          icon="el-icon-download"
          size="mini"
          @click="handleExport"
          >导出
        </el-button>
      </el-col> -->
      <!-- <el-col :span="1.5">
        <el-button
          type="success"
          plain
          size="mini" :disabled="multiple"
          @click="handleSuccessAll"
          >批量入库
        </el-button>
      </el-col>
      <el-col :span="1.5">
          <el-button
            type="danger"
            plain :disabled="multiple"
            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="handleExportInfo">
          导出
        </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>
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="testedList" border ref="multipleTable" row-key="taskId" @selection-change="handleSelectionChange" :max-height="650">
      <el-table-column type="selection" align="center"  :selectable="selectable"/>
      <el-table-column label="序号" align="center" type="index">
        <template slot-scope="scope">
          <span>{{
            (queryParams.pageNum - 1) * queryParams.pageSize + scope.$index + 1
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="分公司" align="center" prop="impUnitName" width="140" />
      <el-table-column label="退料单位" align="center" prop="backUnit"  />
      <el-table-column label="退料工程" align="center" prop="backPro"  />
      <el-table-column label="入库单号" align="center" prop="inputCode"  />
      <el-table-column label="物资类型" align="center" prop="materialType"  />
      <el-table-column label="维修单号" align="center" prop="repairCode"  />
      <el-table-column label="创建人" align="center" prop="createBy"  />
      <el-table-column label="创建时间" align="center" prop="createTime" width="100" />
      <el-table-column label="状态" align="center" prop="taskStatus" >
        <template slot-scope="scope">
          <dict-tag
            :options="dict.type.repair_end_task_status"
            :value="scope.row.taskStatus"
          />
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="180">
        <template slot-scope="scope">
          <el-button
            size="mini"
            style="margin-bottom: 10px"
            type="normal"
            @click="handleView(scope.row)"
            >查看
          </el-button>
          <el-button
            size="mini"
            style="margin-bottom: 10px"
            type="primary"

            @click="handleUpdate(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 {
  getTestedListApi,repairInputWarehouseApi,rejectWarehouseApi
} from "@/api/repair/testedInBound";
import { formatTime } from '@/utils/bonus'

export default {
  name: "Home",
  dicts: ["repair_end_task_status"],
  data() {
    return {
      // 遮罩层
      loading: false,
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,

      // 显示搜索条件
      showSearch: true,
      // 查看页面
      showView: false,
      // 总条数
      total: 0,
      //二级页面总条数
      totalView:0,
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyWord: undefined,
        time: [],
        startTime: undefined,
        endTime: undefined,
        taskStatus: '',
      },
      queryInBoundInfo:{
        pageNum: 1,
        pageSize: 10,
      },
      ids:[],
      //修试入库列表
      testedList:[],
      //审核入库列表
      getInBoundInfo:[]
    };
  },
  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)
    if(this.$route.query.code){
      this.queryParams.keyWord=this.$route.query.code
    }
    // 不在这里直接调用getList，等字典数据加载完成后再调用
  },
  components: {},
  methods: {
    // 字典数据加载完成后的回调
    onDictReady(dict) {
      // 获取repair_end_task_status的所有选项
      const validOptions = dict.type.repair_end_task_status || []

      // 如果有有效选项，设置第一个为默认值
      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}`
    },
    /** 查询修试入库列表 */
    getList() {
      this.loading = true;
      // this.queryParams.startTime = this.queryParams.time ? this.queryParams.time[0] : '';
      // this.queryParams.endTime = this.queryParams.time ? this.queryParams.time[1] : '';
      getTestedListApi(this.queryParams).then((response) => {
        this.testedList = response.data.rows;
        this.total = response.data.total;
        this.loading = false;
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },

    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams.keyWord = null;
      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.handleQuery();
    },
    //一级页面审核按钮
    handleUpdate(row){
      this.$emit("editApply",row.id,row);
    },
    //一级页面查看按钮
    handleView(row){
      this.$emit("queryApply",row.id,row);
    },
    //是否可用勾选框
    selectable(row) {
      if (row.taskStatus == "1"||row.taskStatus == "2") {
        return false;
      } else {
        return true;
      }
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => {
        let obj = {
          agreementId:item.agreementId,
          taskId:item.taskId
        }
        return obj
      });
      this.single = selection.length != 1;
      this.multiple = !selection.length;
    },
    //批量通过
    handleSuccessAll(){
      console.log(this.ids)
      // repairInputWarehouseApi
      let param = {
        outTaskList:this.ids
      }
      this.$modal.confirm("是否确认入库所选择的设备编码？")
        .then(function () {
          return repairInputWarehouseApi(param);
        }).then((response) => {
          if(response.code==200){
            this.$modal.msgSuccess("入库成功");
            this.getList();
          }
        })
        .catch(() => {});
    },
    //批量不通过
    handleFailAll(){
      console.log(this.ids)
      let param = {
        outTaskList:this.ids
      }
      this.$modal.confirm("是否确认驳回所选择的设备编码？")
        .then(function () {
          return rejectWarehouseApi(param);
        }).then((response) => {
          if(response.code==200){
            this.$modal.msgSuccess("驳回成功");
            this.getList();
          }
        })
        .catch(() => {});
    },
    handleExportInfo() {
      try {
        let fileName = `修试后入库_${formatTime(new Date())}.xLsx`
        let url = '/material/repair_input_details/exportInfo'
        const params = { ...this.queryParams }
        console.log('🚀 ~ 导出 ~ params:', params)
        this.download(url, params, fileName)
      } catch (error) {
        console.log('导出数据失败', error)
      }
    },
    handleExport() {
      try {
        let fileName = `修试后入库明细_${formatTime(new Date())}.xLsx`
        let url = '/material/repair_input_details/export'
        const params = { ...this.queryParams }
        console.log('🚀 ~ 导出 ~ params:', params)
        this.download(url, params, fileName)
      } catch (error) {
        console.log('导出数据失败', error)
      }
    },

  },
};
</script>
  <style lang="scss" scoped>
.uploadImg {
  padding-top: 20px;
  display: flex;
  align-items: center;
  justify-content: center;
}
.deviceCode {
  margin-top: 10px;
  padding-bottom: 20px;
  font-size: 18px;
}
::v-deep.el-table .fixed-width .el-button--mini {
  width: 60px !important;
  margin-bottom: 10px;
}
//隐藏图片上传框的css
::v-deep.disabled {
  .el-upload--picture-card {
    display: none;
  }
}
</style>
