<template>
  <div class="app-container">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="small"
      :inline="true"
      v-show="showSearch"
      label-width="100px"
    >
      <el-form-item label="计划名称" prop="planName">
        <el-input
          v-model="queryParams.planName"
          placeholder="请输入计划名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="物资柜" prop="cabinetId">
        <el-select
          :disabled="visibleSelect"
          v-model="queryParams.cabinetId"
          placeholder="请选择物资柜"
          clearable
        >
          <el-option
            v-for="dict in cabinets"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="物资名称" prop="materialsName">
        <el-input
          v-model="queryParams.materialsName"
          placeholder="请输入物资名称"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="物资类型" prop="materialsTypeId">
        <treeselect
          style="width: 215px"
          v-model="queryParams.materialsTypeId"
          :options="materialstypeOptions"
          :normalizer="materialnormalizer"
          placeholder="请选择物资类型"
        />
      </el-form-item>
      <el-form-item label="RFID" prop="materialsRfid">
        <el-input
          v-model="queryParams.materialsRfid"
          placeholder="请输入RFID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="检查时间">
        <el-date-picker
          style="width: 215px"
          :default-time="['00:00:00', '23:59:59']"
          v-model="createTime"
          type="datetimerange"
          :picker-options="pickerOptions"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          align="right"
          @change="handleClearTime"
        >
        </el-date-picker>
      </el-form-item>
      <!--      <el-form-item label="岗位" prop="workstationId">-->
      <!--        <treeselect-->
      <!--          style="width: 218px"-->
      <!--          v-model="queryParams.workstationId"-->
      <!--          :options="marsOptions"-->
      <!--          :normalizer="normalizer"-->
      <!--          placeholder="选择岗位"-->
      <!--        />-->
      <!--      </el-form-item>-->


      <el-form-item label="检查结果" prop="status">
        <el-select v-model="queryParams.status" placeholder="检查结果">
          <el-option
            v-for="dict in dict.type.checks_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="异常原因" prop="reason">
        <el-select v-model="queryParams.reason" placeholder="状态">
          <el-option
            v-for="dict in dict.type.exceptions_status"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button
          v-no-more-click
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="handleQuery"
        >搜索
        </el-button
        >
        <el-button
          v-no-more-click
          icon="el-icon-refresh"
          size="mini"
          @click="resetQuery"
        >重置
        </el-button
        >
      </el-form-item>
    </el-form>
    <el-row :gutter="10" class="mb8">
      <el-button v-no-more-click
                 type="warning"
                 plain
                 icon="el-icon-download"
                 size="mini"
                 @click="handleExport"
                 v-hasPermi="['iscs:check:export']"
      >导出
      </el-button>
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          v-no-more-click-->
      <!--          type="primary"-->
      <!--          plain-->
      <!--          icon="el-icon-plus"-->
      <!--          size="mini"-->
      <!--          @click="handleAdd"-->
      <!--          v-hasPermi="['iscs:check:add']"-->
      <!--        >新增-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          v-no-more-click-->
      <!--          type="danger"-->
      <!--          plain-->
      <!--          icon="el-icon-delete"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--          @click="handleDelete"-->
      <!--          v-hasPermi="['iscs:check:remove']"-->
      <!--        >批量删除-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <right-toolbar
        :showSearch.sync="showSearch"
        @queryTable="getList"
      ></right-toolbar>
    </el-row>
    <el-table
      v-loading="loading"
      :data="RecordList"
      @selection-change="handleSelectionChange"
    >
      <!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="计划名称" align="center" prop="planName" width="200">
        <template slot-scope="scope">
          <span v-if="scope.row.planName">{{scope.row.planName}}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="物资柜" align="center" prop="cabinetName">
      </el-table-column>
      <el-table-column label="物资编号" align="center" prop="materialsId">
      </el-table-column>
      <el-table-column label="物资名称" align="center" prop="materialsName"/>
      <el-table-column label="物资类型" align="center" prop="materialsTypeName"/>
      <el-table-column
        label="物资图片"
        align="center"
        prop="materialsTypePicture"
      >
        <template slot-scope="scope">
          <img
            v-if="scope.row.materialsTypePicture"
            :src="scope.row.materialsTypePicture"
            alt=""
            style="width: 50px; height: 50px"
          />
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="RFID" align="center" prop="materialsRfid">
        <template slot-scope="scope">
          <span v-if="scope.row.materialsRfid">{{scope.row.materialsRfid}}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
        label="检查时间"
        align="center"
        prop="createTime"
        width="250"
      >
        <template slot-scope="scope">
          {{ scope.row.createTime }}
        </template>
      </el-table-column>
      <el-table-column label="检查结果" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.checks_status" :value="scope.row.status"/>
        </template>
      </el-table-column>
      <el-table-column label="异常原因" align="center" prop="reason">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.exceptions_status" :value="scope.row.reason" v-if="scope.row.reason!=='0'"/>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column
        label="措施"
        align="center"
        prop="measure"
      >
        <template slot-scope="scope">
         <span v-if="scope.row.measure">{{scope.row.measure}}</span>
          <span v-else>-</span>
        </template>
      </el-table-column>
      <el-table-column label="更换记录" align="center" prop="status">
        <template slot-scope="scope">
          <el-button type="text" @click="goto(scope.row)">查看</el-button>
        </template>
      </el-table-column>
      <!--      <el-table-column-->
      <!--        label="操作"-->
      <!--        align="center"-->
      <!--        class-name="small-padding fixed-width"-->
      <!--      >-->
      <!--        <template slot-scope="scope">-->
      <!--          <el-button-->
      <!--            v-no-more-click-->
      <!--            size="mini"-->
      <!--            type="text"-->
      <!--            icon="el-icon-edit"-->
      <!--            @click="handleUpdate(scope.row)"-->
      <!--            v-hasPermi="['iscs:check:edit']"-->
      <!--          >编辑-->
      <!--          </el-button>-->

      <!--          <el-button-->
      <!--            v-no-more-click-->
      <!--            size="mini"-->
      <!--            type="text"-->
      <!--            icon="el-icon-delete"-->
      <!--            @click="handleDelete(scope.row)"-->
      <!--            v-hasPermi="['iscs:check:remove']"-->
      <!--          >删除-->
      <!--          </el-button>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.current"
      :limit.sync="queryParams.size"
      @pagination="getList"
    />

  </div>
</template>

<script>
import {
  listCheckRecord, addCheckRecord, updateCheckRecord, deleteCheckRecord, selectCheckRecordById
} from '@/api/mes/material/checkRecord'
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { listMarsDept } from '@/api/system/marsdept'
import { getIsMaterialsCabinets } from '@/api/mes/material/information'
import { listType } from '@/api/mes/material/typeindex'
import Template from '@/views/print/printtemplate/list.vue'
import { listUser } from '@/api/system/user'
import { listPlan } from '@/api/mes/material/plan'

export default {
  name: 'Team',
  components: { Template, Treeselect },
  props: {
    cabinetId: {
      type: String,
      required: false
    },
    planId: {
      type: String,
      required: false
    },
    planName: {
      type: String,
      required: false
    },
  },
  dicts: ['material_status', 'checks_status', 'exceptions_status'],
  data() {
    return {
      //自动生成编码
      autoGenFlag: false,
      optType: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      codes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 弹出层标题
      title: '',
      // 总条数
      total: 0,
      // 检查记录表格数据
      RecordList: [],
      // mars树选项
      marsOptions: [],
// 是否显示弹出层
      open: false,
      // 查询参数
      createTime: '',
      queryParams: {
        current: 1,
        size: 10,
        materialsRfid: '',
        materialsName: null,
        loanState: null,
        materialsCabinetId: null,
        materialsTypeId: null,
        startTime: '',
        endTime: '',
        reason: '',
        status: '',
        planId: null,
        planName: '',
        cabinetId: null
      },
      // 表单参数
      form: {},
      cabinets: [], //物资所属柜
      planPersonOption: [], // 检查人员
      planList: [],//检查计划Id
      workstationOption: [],//所属岗位
      // 表单校验
      rules: {
        userIdStr: [
          { required: true, message: '人员不能为空', trigger: 'blur' }
        ],
        checkName: [
          { required: true, message: '任务名称不能为空', trigger: 'blur' }
        ],
        cron: [
          { required: true, message: '检查时间频率不能为空', trigger: 'blur' }
        ]

      },
      pickerOptions: {
        shortcuts: [
          {
            text: '最近一周',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 7)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近一个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 30)
              picker.$emit('pick', [start, end])
            }
          },
          {
            text: '最近三个月',
            onClick(picker) {
              const end = new Date()
              const start = new Date()
              start.setTime(start.getTime() - 3600 * 1000 * 24 * 90)
              picker.$emit('pick', [start, end])
            }
          }
        ]
      },
      materialstypeOptions: [],
      visibleSelect: false
    }
  },

  created() {
    this.getList()
    this.getTreeselect()
    this.materialsCabinets()

    console.log(this.planId, this.planName, '接收到了 生活时尚生活是')
    if (this.cabinetId) {
      this.visibleSelect = true
    }
  },

  methods: {
    goto(row) {
      if (this.cabinetId) {
        this.$emit('recordId', row.recordId)
      } else {
        this.$router.push({
          path: '/material/replacementrecords',
          query: {
            recordId: row.recordId
          }
        })
      }

    },
    formatDate(date) {
      const year = date.getFullYear().toString().padStart(2, '0')
      const month = (date.getMonth() + 1).toString().padStart(2, '0')
      const day = date.getDate().toString().padStart(2, '0')
      const hours = date.getHours().toString().padStart(2, '0')
      const minutes = date.getMinutes().toString().padStart(2, '0')
      const seconds = date.getSeconds().toString().padStart(2, '0')

      return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
    },
    /** 查询物资信息列表 */
    getList() {
      this.loading = true

      // 格式化日期并更新 queryParams
      if (Array.isArray(this.createTime) && this.createTime.length === 2) {
        this.queryParams.startTime = this.formatDate(this.createTime[0])
        this.queryParams.endTime = this.formatDate(this.createTime[1])
      }
      // 更新 queryParams 从路由查询参数

      if (this.$route.query.planName) {
        this.queryParams.planName = this.$route.query.planName
      }
      if (this.$route.query.planId) {
        this.queryParams.planId = this.$route.query.planId
      }
      // 更新 queryParams 从 props
      if (this.planName) {
        this.queryParams.planName = this.planName
      }
      if (this.planId) {
        this.queryParams.planId = this.planId
      }

      if (this.$route.query.cabinetId) {
        this.queryParams.cabinetId = this.$route.query.cabinetId
      }
      if (this.cabinetId) {
        this.queryParams.cabinetId = this.cabinetId
      }
      const data = {
        ...this.queryParams
      }
      listCheckRecord(data).then((response) => {
        console.log(response, 'response')
        this.RecordList = response.data.records
        this.total = response.data.total
        this.loading = false
      })

    },
    /** 查询物资类型下拉树结构 */
    getTreeselect() {
      const data = {
        current: 1,
        size: -1
      }
      listType(data).then((response) => {
        console.log(response, '物资类型树形结构')
        this.materialstypeOptions = this.handleTree(
          response.data.records,
          'materialsTypeId',
          'parentId',
          'children'
        )
      })
    },
    /** 查询物资柜结构 */
    materialsCabinets() {
      const data2 = {
        current: 1,
        size: -1
      }
      getIsMaterialsCabinets(data2).then((response) => {
        if (response?.data?.records) {
          // 提取 cabinetId 和 cabinetName
          this.cabinets = response.data.records.map((item) => ({
            value: item.cabinetId,
            label: item.cabinetName
          }))
        }
      })
      // 岗位查询
      const data3 = {
        pasge: 1,
        size: -1,
        parentId: '0'
      }
      listMarsDept(data3).then((response) => {
        this.marsOptions = this.handleTree(response.data.records, 'workstationId', 'parentId')
      })
      const data1 = {
        pageSize: 999999999,
        pageNum: 1
      }
      listUser(data1).then((res) => {
        this.planPersonOption = res.rows.map((item) => {
          return {
            label: item.nickName,
            value: item.userId
          }
        })
      })
      listPlan(data2).then((response) => {
        this.planList = response.data.records.map((item) => {
          return {
            label: item.planName,
            value: item.planId
          }
        })
      })
    },
    /** 查询岗位下拉树结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.workstationId,
        label: node.workstationName,
        children: node.children
      }
    },
    /** 查询物资类型下拉树结构 */
    materialnormalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.materialsTypeId,
        label: node.materialsTypeName,
        children: node.children
      }
    },

// 取消按钮
    cancel() {
      this.open = false
      this.reset()
    },
    // 表单重置
    reset() {
      this.resetForm('form')
      this.autoGenFlag = false
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.current = 1
      // 在调用 getList 前确保查询条件保留输入框的值
      this.queryParams.planName =this.queryParams.planName|| null
      this.queryParams.cabinetId =this.queryParams.cabinetId|| null
      this.queryParams.planId =this.queryParams.planId|| null
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.startTime = ''
      this.queryParams.endTime = ''
      this.createTime = ''
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.recordId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.form.workstationId = null
      this.title = '新增检查记录'
      this.optType = 'add'
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      selectCheckRecordById(row.recordId).then((response) => {
        this.form = response.data
        this.open = true
        this.title = '编辑检查记录'
        this.optType = 'edit'
      })
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.form.recordId != null) {
            updateCheckRecord(this.form).then((response) => {
              console.log(response, '修改返回')
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addCheckRecord(this.form).then((response) => {
              console.log(response, '新增返回')
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const checkIds = row.recordId || this.ids

      this.$modal
        .confirm('是否确认删除编号为"' + checkIds + '"的数据项？')
        .then(function() {
          return deleteCheckRecord(checkIds)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {
        })
    },

    /** 导出按钮操作 */
    handleExport() {
      this.download('iscs/check/exportIsMaterialsCheckRecord', {
        ...this.queryParams
      }, `records_${new Date().getTime()}.xlsx`)
    },
    //   检查日期清空
    handleClearTime(value){
      if(value==null){
        this.queryParams.startTime=null
        this.queryParams.endTime=null
      }
    }
  }
}
</script>
<style lang="scss" src="@/assets/styles/dialog-title.scss" scoped>
.el-input-width {
  width: 380px !important;

}
</style>
