<template>
  <!-- 基础页面 -->
  <div class="app-container">
    <el-form v-show="showSearch" :model="queryParams" ref="queryForm" size="small" inline @submit.native.prevent label-width="100px">
      <el-form-item label="综合搜索" prop="keyWord">
        <el-input
          v-model="queryParams.keyWord"
          placeholder="输入『 物资名称 / 设备编码 / 本次检验人 』关键字搜索"
          clearable
          @keyup.enter.native="handleQuery"
          style="width: 380px"
        />
      </el-form-item>

      <el-form-item label="分公司" prop="impUnitName">
        <el-select
          v-model="queryParams.impUnitName"
          placeholder="请选择分公司"
          clearable
          filterable
          style="width: 240px"
          @change="handleImpUnitChange"
        >
          <el-option
            v-for="item in impUnitOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="项目部" prop="departName">
        <el-select
          v-model="queryParams.departName"
          placeholder="请选择项目部"
          clearable
          filterable
          style="width: 240px"
        >
          <el-option
            v-for="item in departOptions"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          />
        </el-select>
      </el-form-item>

      <!-- 日期范围 -->
      <el-form-item label="本次检验时间" prop="checkStartTime">
        <el-date-picker
          v-model="queryParams.checkStartTime"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="开始日期"
          @change="() => queryParams.checkEndTime = ''"
          style="width: 130px"
        />
      </el-form-item>
      <el-form-item>-</el-form-item>
      <el-form-item prop="checkEndTime">
        <el-date-picker
          v-model="queryParams.checkEndTime"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="结束日期"
          :picker-options="{ disabledDate: (t) => t.getTime() < new Date(queryParams.checkStartTime).getTime() - 86400000}"
          style="width: 130px"
        />
      </el-form-item>

      <!-- 日期范围 -->
      <el-form-item label="下次检验时间" prop="nextStartTime">
        <el-date-picker
          v-model="queryParams.nextStartTime"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="开始日期"
          @change="() => queryParams.nextEndTime = ''"
          style="width: 130px"
        />
      </el-form-item>
      <el-form-item>-</el-form-item>
      <el-form-item prop="nextEndTime">
        <el-date-picker
          v-model="queryParams.nextEndTime"
          value-format="yyyy-MM-dd"
          type="date"
          placeholder="结束日期"
          :picker-options="{ disabledDate: (t) => t.getTime() < new Date(queryParams.nextStartTime).getTime() - 86400000}"
          style="width: 130px"
        />
      </el-form-item>

      <!-- 日期范围 -->
      <el-form-item label="进站时间" 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 label="设备类型" prop="typeCodeId">
        <el-select
          v-model="queryParams.typeCodeId"
          placeholder="请选择设备类型"
          clearable
          filterable
          style="width: 240px"
          @change="handleType"
        >
          <el-option v-for="(item, index) in typeCodeOpts" :key="index" :label="item.typeName" :value="item.typeId" />
        </el-select>
      </el-form-item> -->
      <!-- <el-form-item label="规格型号" prop="maModel">
        <el-input
          v-model="queryParams.maModel"
          placeholder="请输入规格型号"
          clearable
          :maxlength="99"
          style="width: 240px"
        />
      </el-form-item> -->
      <!-- 表单按钮 -->
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" @click="handleQuery">查询</el-button>
        <el-button icon="el-icon-refresh" @click="handleReset">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table :data="tableList" fit highlight-current-row style="width: 100%">
      <el-table-column
        type="index"
        width="55"
        label="序号"
        align="center"
        :index="index => (queryParams.pageNum - 1) * queryParams.pageSize + index + 1"
      />
      <el-table-column
        v-for="(column, index) in tableColumns"
        show-overflow-tooltip
        :key="index"
        :label="column.label"
        :prop="column.prop"
        align="center"
      >
        <!-- 插槽 -->
        <template v-slot="{ row }" v-if="column.prop == 'qrCode'">
          <span>
            <el-button v-if="row.qrCode" type="text" size="mini" @click="handleSee(row)">查看</el-button>
            <span v-else>未绑定</span>
          </span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 二维码 -->
    <QRCodeView ref="qrCodeView" />
  </div>
</template>

<script>
import Treeselect from '@riophae/vue-treeselect'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'
import QRCodeView from '@/components/QRCodeView'
import { getMachineInfoApi, getLevelListApi,getImpUnitListApi,getDepartListByImpUnitApi } from '@/api/materialsStation'

export default {
  components: { Treeselect, QRCodeView },
  data() {
    return {
      showSearch: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        keyWord: '', // 关键字
        typeCodeId: undefined, // 设备类型ID
        typeCode: '', // 设备类型
        maModel: '', // 规格型号
        impUnitName: '', // 分公司
        departName: '', // 项目部
        thisCheckTimeRange: [], // 本次检验时间
        nextCheckTimeRange: [], // 下次检验时间
        inputTimeRange: [], // 进站时间
        startTime: '', // 进站开始时间
        endTime: '', // 进站结束时间
        checkStartTime: '', // 本次检验开始时间
        checkEndTime: '', // 本次检验结束时间
        nextStartTime: '', // 下次检验开始时间
        nextEndTime: '', // 下次检验结束时间
      },
      typeCodeOpts: [], // 设备类型
      modelTypeOpts: [], // 规格型号
      total: 0, // 总条数
      // 表头
      tableColumns: [
        { label: '分公司', prop: 'impUnitName' },
        { label: '项目部', prop: 'departName' },
        { label: '领料单位', prop: 'leaseUnit' },
        { label: '领料工程', prop: 'leaseProject' },
        { label: '物资名称', prop: 'typeName' },
        { label: '规格型号', prop: 'maModel' },
        { label: '设备编码', prop: 'maCode' },
        // { label: '设备状态', prop: 'maStatus' },
        { label: '本次检验时间', prop: 'thisCheckTime' },
        { label: '本次检验人员', prop: 'checkMan' },
        { label: '下次检验时间', prop: 'nextCheckTime' },
        { label: '二维码', prop: 'qrCode' },
        { label: '进站时间', prop: 'inputTime' }
      ],
      // 表格数据
      tableList: [],
      impUnitOptions: [],   // 分公司下拉
      departOptions: [],    // 项目部下拉

    }
  },
  created() {
    this.getImpUnitOptions()
    this.handleImpUnitChange()
    this.getList()
    // this.getModelType()
  },
  methods: {
    /** 获取分公司下拉 */
    async getImpUnitOptions() {
      try {
        const res = await getImpUnitListApi() // 调后台接口
        this.impUnitOptions = res.data.map(item => ({
          label: item.impUnitName,   // 这里根据实际字段替换
          value: item.impUnitName
        }))
      } catch (e) {
        console.error('获取分公司下拉失败:', e)
      }
    },
    /** 分公司选择变化，加载项目部 */
    async handleImpUnitChange() {
      this.queryParams.departName = null // 清空项目部已选
      this.departOptions = []            // 清空原有下拉

      try {
        const params = {
          impUnitName: this.queryParams.impUnitName, // 分公司名称
        }
        const res = await getDepartListByImpUnitApi(params)
        this.departOptions = res.data.map(item => ({
          label: item.departName,   // 项目部名称字段
          value: item.departName
        }))
      } catch (e) {
        console.error('获取项目部下拉失败:', e)
      }
    },


    /** 转换菜单数据结构 */
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children
      }
    },

    // 查询
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 重置
    handleReset() {
      this.queryParams.pageNum = 1
      this.queryParams.pageSize = 10
      this.$refs.queryForm.resetFields()
      this.queryParams.thisCheckTimeRange = []
      this.queryParams.nextCheckTimeRange = []
      this.queryParams.inputTimeRange = []
      this.queryParams.checkStartTime = ''
      this.queryParams.checkEndTime = ''
      this.queryParams.nextStartTime = ''
      this.queryParams.nextEndTime = ''
      this.queryParams.startTime = ''
      this.queryParams.endTime = ''
      this.getImpUnitOptions()
      this.handleImpUnitChange()
      this.getList()
    },
    // 获取列表
    async getList() {
      console.log('列表-查询', this.queryParams)
      const loading = this.$loading({ text: '加载中...' })
      // this.queryParams.startTime = this.queryParams.inputTimeRange ? this.queryParams.inputTimeRange[0] : ''
      // this.queryParams.endTime = this.queryParams.inputTimeRange ? this.queryParams.inputTimeRange[1] : ''
      // this.queryParams.checkStartTime = this.queryParams.thisCheckTimeRange? this.queryParams.thisCheckTimeRange[0] : ''
      // this.queryParams.checkEndTime = this.queryParams.thisCheckTimeRange? this.queryParams.thisCheckTimeRange[1] : ''
      // this.queryParams.nextStartTime = this.queryParams.nextCheckTimeRange? this.queryParams.nextCheckTimeRange[0] : ''
      // this.queryParams.nextEndTime = this.queryParams.nextCheckTimeRange? this.queryParams.nextCheckTimeRange[1] : ''
      try {
        const params = { ...this.queryParams }
        const res = await getMachineInfoApi(params)
        console.log('🚀 ~ 获取列表 ~ res:', res)
        this.tableList = res.data.rows
        this.total = res.data.total
        loading.close()
      } catch (error) {
        console.log('🚀 ~ 获取列表 ~ error:', error)
        this.tableList = []
        this.total = 0
        loading.close()
      }
    },
    // 获取设备类型树
    async getModelType() {
      try {
        const res = await getLevelListApi({ level: 3 })
        const res2 = await getLevelListApi({ level: 4 })
        this.typeCodeOpts = res.data
        this.modelTypeOpts = res2.data
      } catch (error) {
        console.log('获取设备类型树失败', error)
      }
    },
    handleType(val) {
      console.log('🚀 ~ handleType ~ val:', val)
      this.queryParams.typeCode = this.typeCodeOpts.find(item => item.typeId === val)?.typeName || ''
    },
    handleModel(val) {
      console.log('🚀 ~ handleModel ~ val:', val)
      this.queryParams.maModel = this.modelTypeOpts.find(item => item.typeId === val)?.typeName || ''
    },
    // normalizer(node) {
    //   if (node.children && !node.children.length) {
    //     delete node.children
    //   }
    //   return {
    //     id: node.typeId,
    //     label: node.typeName,
    //     children: node.children
    //   }
    // },
    handleSee(row) {
      this.$refs.qrCodeView.showQRCode(row.qrCode, row.maCode)
    }
  }
}
</script>

<style lang="scss" scoped></style>
