<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="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="materialsTypeId">
        <treeselect
          style="width: 215px"
          v-model="queryParams.materialsTypeId"
          :options="materialstypeOptions"
          :normalizer="materialnormalizer"
          placeholder="请选择物资类型"
        />
      </el-form-item>

      <el-form-item label="原物资编号" prop="oldMaterialsId">
        <el-input
          v-model="queryParams.oldMaterialsId"
          placeholder="请输入原物资编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>

      <el-form-item label="原RFID" prop="oldMaterialsRfid">
        <el-input
          v-model="queryParams.oldMaterialsRfid"
          placeholder="请输入原RFID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="新物资编号" prop="newMaterialsId">
        <el-input
          v-model="queryParams.newMaterialsId"
          placeholder="请输入新物资编号"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="新RFID" prop="newMaterialsRfid">
        <el-input
          v-model="queryParams.newMaterialsRfid"
          placeholder="请输入新RFID"
          clearable
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="更换人" prop="changeUserName">
        <el-input
          v-model="queryParams.changeUserName"
          placeholder="请输入更换人"
          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>
        <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-col :span="1.5">-->
<!--        <el-button-->
<!--          v-no-more-click-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          size="mini"-->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['iscs:change: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:change:remove']"-->
<!--        >批量删除-->
<!--        </el-button>-->
<!--      </el-col>-->
<!--    </el-row>-->
    <el-table
      v-loading="loading"
      :data="changeRecordList"
      @selection-change="handleSelectionChange"
    >
<!--      <el-table-column type="selection" width="55" align="center"/>-->
      <el-table-column label="物资柜" align="center" prop="cabinetName">
        <template slot-scope="scope">
          <span v-if="scope.row.cabinetName">{{scope.row.cabinetName}}</span>
          <span v-else>-</span>
        </template>
      </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="原物资编号" align="center" prop="oldMaterialsId">
      </el-table-column>
      <el-table-column label="原物资名称" align="center" prop="oldMaterialsName">
      </el-table-column>
      <el-table-column label="原RFID" align="center" prop="oldMaterialsRfid">
      </el-table-column>
      <el-table-column label="新物资编号" align="center" prop="newMaterialsId">
      </el-table-column>
      <el-table-column label="新物资名称" align="center" prop="newMaterialsName">
      </el-table-column>
      <el-table-column label="新RFID" align="center" prop="newMaterialsRfid">
      </el-table-column>
      <el-table-column
        label="更换人"
        align="center"
        prop="changeUserName"
      >
      </el-table-column>
      <el-table-column label="更换时间" align="center" prop="changeDate">
        <template slot-scope="scope">
          <span v-if="scope.row.changeDate">{{scope.row.changeDate}}</span>
          <span v-else>-</span>
        </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:change:edit']"-->
<!--          >编辑-->
<!--          </el-button>-->

<!--          <el-button-->
<!--            v-no-more-click-->
<!--            size="mini"-->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['iscs:change: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"
    />
    <!-- 添加或修改班组对话框 -->
    <el-dialog :visible.sync="open" width="500px" append-to-body>
      <div slot="title" class="dialog-title">
        <i></i>
        <span class="title">{{ title }}</span>
      </div>
      <el-form ref="form" :model="form" :rules="rules" label-width="110px">
        <el-form-item label="计划名称Id" prop="planId">
          <el-select
            style="width: 348px"
            v-model="form.planId"
            placeholder="请选择检查计划"
            clearable
          >
            <el-option
              v-for="dict in planList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="更换日期">
          <el-date-picker
            style="width: 350px"
            v-model="form.changeDate"
            placeholder="请选择日期"
            :picker-options="pickerOptions"
            align="right"
          >
          </el-date-picker>
        </el-form-item>
        <!--        <el-form-item label="所属岗位" prop="workstationId">-->
        <!--          <treeselect  style="width: 348px" v-model="form.workstationId" :options="workstationOption"-->
        <!--                       :normalizer="normalizer" placeholder="选择岗位"-->
        <!--          />-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="检查物资柜" prop="cabinetIds">-->
        <!--          <el-select-->
        <!--            style="width: 348px"-->
        <!--            v-model="form.cabinetIds"-->
        <!--            placeholder="请选择需要检查的物资柜"-->
        <!--            multiple-->
        <!--            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="changeUserId">
          <el-select
            style="width: 348px"
            v-model="form.changeUserId"
            placeholder="请选择更换员"
            clearable
          >
            <el-option
              v-for="dict in planPersonOption"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="检查记录Id" prop="checkRecordId">
          <el-input
            v-model="form.checkRecordId"
            placeholder="请输入检查记录Id"
            clearable
          />
        </el-form-item>
<!--        <el-form-item label="物资Id" prop="materialsId">-->
<!--          <el-input-->
<!--            v-model="form.materialsId"-->
<!--            placeholder="请输入物资Id"-->
<!--            clearable-->
<!--          />-->
<!--        </el-form-item>-->
        <el-form-item label="新物资Id" prop="newMaterialsId">
          <el-input
            v-model="form.newMaterialsId"
            placeholder="请输入新物资Id"
            clearable
          />
        </el-form-item>
        <el-form-item label="新物资RFID" prop="newMaterialsRfid">
          <el-input
            v-model="form.newMaterialsRfid"
            placeholder="请输入新物资RFID"
            clearable
          />
        </el-form-item>
        <el-form-item label="原物资Id" prop="oldMaterialsId">
          <el-input
            v-model="form.oldMaterialsId"
            placeholder="请输入原物资Id"
            clearable
          />
        </el-form-item>
        <el-form-item label="原物资Rfid" prop="oldMaterialsRfid">
          <el-input
            v-model="form.oldMaterialsRfid"
            placeholder="请输入原物资Rfid"
            clearable
          />
        </el-form-item>
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button v-no-more-click type="primary" @click="submitForm"
        >确 定
        </el-button>
        <el-button v-no-more-click @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listChangeRecord,addChangeRecord,updateChangeRecord,deleteChangeRecord,selectChangeRecordById
} from '@/api/mes/material/replace'

import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import { listMarsDept } from '@/api/system/marsdept'
import { listType } from '@/api/mes/material/typeindex'
import Template from '@/views/print/printtemplate/list.vue'
import { getIsMaterialsCabinets } from '@/api/mes/material/information'
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
    },
    recordId: {
      type:String,
      required:false
    }

  },
  dicts: ['material_status','checking_status'],
  data() {
    return {
      //自动生成编码
      autoGenFlag: false,
      optType: undefined,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      codes: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 班组表格数据
      changeRecordList: [],
      // mars树选项
      marsOptions: [],
      // 是否显示弹出层
      open: false,
      // 查询参数
      createTime: '',
      queryParams: {
        current: 1,
        size: 10,
        materialsCabinetId: null,
        materialsTypeId: null,
        startTime: '',
        endTime: '',
        oldMaterialsId:'',
        oldMaterialsRfid:'',
        newMaterialsId:'',
        newMaterialsRfid:'',
        changeUserName:'',
        recordId:''
      },
      title:'',
      // 表单参数
      form: {},
      cabinets: [], //物资所属柜
      planPersonOption: [],// 检查人员
      planList:[],//检查计划下拉
      // 表单校验
      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() {
    if(this.cabinetId){
      this.visibleSelect=true
    }
    this.getList()
    this.getTreeselect()
    this.materialsCabinets()
  },

  methods: {
    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])
      }
      if(this.cabinetId){
        this.queryParams.cabinetId = this.cabinetId||''
      }
      if(this.$route.query.recordId||this.recordId){
        this.queryParams.recordId=this.$route.query.recordId||this.recordId||''
      }
      const data={
        ...this.queryParams,
      }
      listChangeRecord(data).then((response) => {
        console.log(response, '获取物资信息allList ')
        this.changeRecordList = 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 data1 = {
        pasge: 1,
        size: -1
      }
      getIsMaterialsCabinets(data1).then((response) => {
        if (response?.data?.records) {
          this.cabinets = response.data.records.map((item) => ({
            value: item.cabinetId,
            label: item.cabinetName
          }))
        }
      })
      // 岗位查询
      listMarsDept(data1).then((response) => {
        this.marsOptions = this.handleTree(response.data.records,"workstationId","parentId")
      })
      // 巡检人员
      const data = {
        pageNum: 1,
        pageSize: 99999
      }
      listUser(data).then((res) => {
        this.planPersonOption = res.rows.map((item) => {
          return {
            label: item.nickName,
            value: item.userId
          }
        })
      })
      listPlan(data1).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.form = {
        cron: undefined
      }
      this.resetForm('form')
      this.autoGenFlag = false
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.size = 10
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm('queryForm')
      this.queryParams.startTime = ''
      this.queryParams.endTime = ''
      this.createTime=''
      this.handleQuery()
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => item.changeId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '新增更换记录'
      this.optType = 'add'
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset()
      selectChangeRecordById(row.changeId).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.changeId != null) {
            updateChangeRecord(this.form).then((response) => {
              console.log(response, '修改返回')
              this.$modal.msgSuccess('修改成功')
              this.open = false
              this.getList()
            })
          } else {
            addChangeRecord(this.form).then((response) => {
              console.log(response, '新增返回')
              this.$modal.msgSuccess('新增成功')
              this.open = false
              this.getList()
            })
          }
        }
      })
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const changeIds = row.changeId || this.ids

      this.$modal
        .confirm('是否确认删除编号为"' + changeIds + '"的数据项？')
        .then(function() {
          return deleteChangeRecord(changeIds)
        })
        .then(() => {
          this.getList()
          this.$modal.msgSuccess('删除成功')
        })
        .catch(() => {
        })
    },
    //   检查日期清空
    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>
