<template>
  <!-- 基础页面 -->
  <div class="app-container">
    <el-form
      v-show="showSearch"
      :model="queryParams"
      ref="queryForm"
      size="small"
      inline
      :rules="rules"
      :disabled="routerParams.isDetails"
      @submit.native.prevent
    >
      <el-form-item label="退料工程" prop="proId">
        <el-select
          v-model="queryParams.proId"
          placeholder="请选择退料工程"
          clearable
          filterable
          :disabled="!routerParams.isAdd"
          @change="handleProChange"
          style="width: 240px"
        >
          <el-option v-for="item in projectList" :key="item.proId" :label="item.proName" :value="item.proId" />
        </el-select>
      </el-form-item>
      <el-form-item label="退料单位" prop="unitId">
        <el-select
          v-model="queryParams.unitId"
          placeholder="请选择退料单位"
          clearable
          :disabled="!routerParams.isAdd"
          @change="changeUnit"
          style="width: 240px"
        >
          <el-option v-for="item in unitList" :key="item.unitId" :label="item.unitName" :value="item.unitId" />
        </el-select>
      </el-form-item>
      <el-form-item label="退料人" prop="backPerson">
        <el-input v-model="queryParams.backPerson" placeholder="请输入退料人" clearable style="width: 240px" />
      </el-form-item>
      <el-form-item label="退料时间" prop="backTime">
        <el-date-picker
          v-model="queryParams.backTime"
          type="date"
          placeholder="退料时间"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          style="width: 240px"
        />
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5" v-if="!routerParams.isDetails">
        <el-button type="primary" plain icon="el-icon-check" size="mini" @click="submit(1)">提 交</el-button>
        <el-button type="primary" plain icon="el-icon-finished" size="mini" @click="submit(0)">暂 存</el-button>
      </el-col>
      <el-col :span="1.5" :offset="0">
        <el-input
          v-model="searchKey"
          placeholder="请输入关键字搜索"
          size="mini"
          clearable
          style="width: 200px; margin-bottom: 10px"
          @keyup.enter="searchTable"
        />
      </el-col>
      <el-col :span="1.5" :offset="0">
        <el-button type="primary" size="mini" @click="searchTable">搜 索</el-button>
      </el-col>
    </el-row>

    <el-table
      ref="tableRef"
      :data="tableList"
      fit
      highlight-current-row
      style="width: 100%"
      v-loading="isLoading"
      :max-height="650"
    >
      <el-table-column type="index" width="55" label="序号" align="center" />
      <el-table-column
        v-for="(column, index) in tableColumns"
        show-overflow-tooltip
        :key="index"
        :label="column.label"
        :prop="column.prop"
        :width="column.width"
        align="center"
      >
        <template v-slot="{ row }" v-if="column.prop == 'manageType'">
          <span>{{ row.manageType == 1 ? '数量管理' : '编码管理' }}</span>
        </template>
        <template v-slot="{ row }" v-else-if="column.prop == 'backNum'">
          <span v-if="!routerParams.isDetails">
            <el-input-number
              v-model="row.backNum"
              placeholder="请输入退料数量"
              clearable
              :controls="false"
              style="width: 100%"
              @change="handleBackNum(row)"
            />
          </span>
          <span v-else>{{ row.backNum }}</span>
        </template>
        <template v-slot="{ row }" v-else-if="column.prop == 'remark'">
          <span v-if="!routerParams.isDetails">
            <el-input v-model="row.remark" placeholder="请输入备注" clearable :controls="false" style="width: 100%" />
          </span>
          <span v-else>{{ row.remark }}</span>
        </template>
      </el-table-column>
      <el-table-column v-if="!routerParams.isDetails" label="操作" align="center" width="100">
        <template slot-scope="{ row, $index }">
          <el-button type="text" size="mini" icon="el-icon-delete" @click="handleDelete($index)" style="color: #f56c6c">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>
  </div>
</template>

<script>
import {
  getListProject,
  getProDepartmentByProApi,
  getUseTypeListApi,
  addBackAppointmentApi,
  editBackAppointmentApi,
  getListDetailsApi
} from '@/api/materialsStation'
import { formatTime } from '@/utils/bonus.js'

export default {
  data() {
    return {
      isSubmit: false,
      isLoading: false,
      showSearch: true,
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() > Date.now()
        }
      },
      queryParams: {
        unitId: '', // 退料单位
        proId: '', // 退料工程
        projectId: '',
        backPerson: '', // 退料人
        backTime: '', // 退料时间
        agreementId: ''
      },
      rules: {
        unitId: [{ required: true, message: '请选择退料单位', trigger: 'change' }],
        proId: [{ required: true, message: '请选择退料工程', trigger: 'change' }],
        backPerson: [{ required: true, message: '请输入退料人', trigger: 'blur' }],
        backTime: [{ required: true, message: '请选择退料时间', trigger: 'change' }]
      },
      projectList: [],
      unitList: [],
      total: 0, // 总条数
      // 表头
      tableColumns: [
        { label: '物资名称', prop: 'typeName' },
        { label: '规格型号', prop: 'typeModel' },
        { label: '计量单位', prop: 'unitName' },
        { label: '当前再用量', prop: 'num' },
        { label: '管理模式', prop: 'manageType' },
        { label: '退料数量', prop: 'backNum', width: 200 },
        { label: '备注', prop: 'remark', width: 200 }
      ],
      // 表格数据
      tableList: [],
      routerParams: {},
      searchKey: '', // 输入的关键字
      currentIndex: -1 // 当前定位到的行
    }
  },
  created() {
    this.routerParams = this.$route.query
    this.routerParams.isAdd = JSON.parse(this.routerParams.isAdd)
    this.routerParams.isDetails = JSON.parse(this.routerParams.isDetails)
    console.log('🚀 ~ created ~ this.routerParams:', this.routerParams)
    let obj = {}
    if (this.routerParams.isAdd) {
      obj = Object.assign({}, this.$route, { title: '新增退料预约' })
      this.$tab.updatePage(obj)
    } else if (!this.routerParams.isAdd && !this.routerParams.isDetails) {
      obj = Object.assign({}, this.$route, { title: '编辑退料预约' })
      this.$tab.updatePage(obj)
      this.getDetails()
    } else {
      // 获取详情
      this.getDetails()
    }
    this.projectInfoList()
  },
  methods: {
    searchTable() {
      if (!this.searchKey) return this.$message.warning('请输入关键字')

      // 查找 tableList 中第一个匹配的数据
      const index = this.tableList.findIndex(item =>
        Object.values(item).some(val => String(val).includes(this.searchKey))
      )

      if (index === -1) {
        this.$message.error('未找到匹配的数据')
        return
      }

      this.currentIndex = index

      // 高亮该行
      this.$refs.tableRef.setCurrentRow(this.tableList[index])

      // 滚动到该行
      this.$nextTick(() => {
        const rowEl = this.$refs.tableRef.$el.querySelectorAll('.el-table__body-wrapper tbody tr')[index]
        if (rowEl) rowEl.scrollIntoView({ behavior: 'smooth', block: 'center' })
      })
    },
    async projectInfoList() {
      try {
        const res = await getListProject({ unitId: null, isApp: true })
        this.projectList = res.data
      } catch (error) {
        console.log('🚀 ~ projectInfoList ~ error:', error)
      }
    },
    async GetUnitData() {
      try {
        const res = await getProDepartmentByProApi({ proId: this.queryParams.proId })
        this.unitList = res.data || []
      } catch (error) {
        console.log('🚀 ~ GetUnitData ~ error:', error)
      }
    },
    handleProChange(e) {
      console.log('🚀 ~ handleProChange ~ e:', e)
      this.unitList = []
      this.queryParams.unitId = ''
      this.queryParams.agreementId = ''
      this.queryParams.projectId = this.projectList.find(item => item.proId === e)?.projectId
      this.GetUnitData()
    },
    changeUnit(e) {
      console.log('🚀 ~ changeUnit ~ e:', e)
      if (!e) return
      const { agreementId } = this.unitList.find(item => item.unitId === e)
      console.log('🚀 ~ changeUnit ~ obj:', agreementId)
      this.queryParams.agreementId = agreementId
      this.getList(agreementId)
    },
    // 获取列表
    async getList(agreementId) {
      this.isLoading = true
      try {
        console.log('🚀 ~ getList ~ params:', agreementId)
        const res = await getUseTypeListApi({ agreementId })
        console.log('🚀 ~ 获取列表 ~ res:', res)
        this.tableList = res.data || []
        this.total = res.data || 0
      } catch (error) {
        console.log('🚀 ~ 获取列表 ~ error:', error)
        this.tableList = []
        this.total = 0
      } finally {
        this.isLoading = false
      }
    },
    // 获取详情
    async getDetails() {
      this.isLoading = true
      try {
        const res = await getListDetailsApi({ id: this.routerParams.id })
        console.log('🚀 ~ 获取详情 ~ res:', res)
        this.queryParams = { ...res.data }
        console.log('🚀 ~ getDetails ~ this.queryParams:', this.queryParams.unitId)
        this.tableList = res.data.backPreDetailsList
        this.$nextTick(() => {
          this.GetUnitData()
        })
      } catch (error) {
        console.log('🚀 ~ 获取详情 ~ error:', error)
      } finally {
        this.isLoading = false
      }
    },
    handleBackNum(row) {
      console.log('🚀 ~ handleBackNum ~ row:', row)
      if (row.backNum > row.num) {
        row.backNum = row.num
        return this.$message.warning('退料数量不能大于当前再用量')
      }
    },
    handleDelete(index) {
      this.tableList.splice(index, 1)
    },
    submit(status) {
      console.log('🚀 ~ submit ~ status:', status)
      // 校验表单数据 queryForm
      this.$refs.queryForm.validate(valid => {
        if (!valid) return

        if (this.isSubmit) return
        const list = this.tableList.filter(item => item.backNum > 0)
        console.log('🚀 ~ submit ~ list:', list)
        if (list.length === 0) return this.$message.warning('请填写退料数量')
        // 二次确认
        let tip = status === 1 ? '是否确定提交？' : '是否确定暂存？'
        this.$confirm(tip, '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
          .then(async () => {
            this.isSubmit = true
            this.isLoading = true
            try {
              const params = {
                ...this.queryParams,
                status,
                backPreDetailsList: list
              }
              console.log('🚀 ~ submit ~ params:', params)
              if (this.routerParams.isAdd) {
                await addBackAppointmentApi(params)
              } else {
                await editBackAppointmentApi(params)
              }
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
              this.$tab.closePage()
            } catch (error) {
              console.log('🚀 ~ submit ~ error:', error)
            } finally {
              this.isLoading = false
              this.isSubmit = false
            }
          })
          .catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            })
          })
      })
    },
  }
}
</script>

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