<template>
  <uni-nav-bar dark :fixed="true" shadow background-color="#4AA4EA" status-bar :title="title"
    ><template v-slot:left>
      <view style="font-size: 18px; display: flex; align-items: center" @click="back">
        <!-- 图标 -->
        <uni-icons type="left" size="20" color="#fff"></uni-icons>
        <!-- 文本 -->
        <text>返回</text>
      </view>
    </template>
    <template v-slot:right>
      <view style="font-size: 18px; display: flex; align-items: center" @click="submit(0)">
        <!-- 文本 -->
        <text>暂存</text>
      </view>
    </template>
  </uni-nav-bar>
  <div class="content">
    <uni-section title="任务信息" type="line"></uni-section>
    <uni-forms ref="form" :rules="rules" :model="formData" label-width="80px">
      <uni-forms-item label="退料班组" required name="teamId">
        <uni-data-select
          v-if="!opts.isEdit"
          v-model="formData.teamId"
          :localdata="teamRange"
          :clear="false"
          filterable
          :disabled="opts.isEdit"
          @change="changeTeamd"
        ></uni-data-select>
        <uni-easyinput v-else v-model="formData.teamName" disabled></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item label="工程名称" required name="projectId">
        <uni-data-select
          v-if="!opts.isEdit"
          v-model="formData.projectId"
          :localdata="prodRange"
          :clear="false"
          filterable
          :disabled="opts.isEdit || !formData.teamId"
          @change="changeProd"
        ></uni-data-select>
        <uni-easyinput v-else v-model="formData.proName" disabled></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item label="退料人员" required name="backPerson">
        <uni-easyinput
          v-model="formData.backPerson"
          placeholder="请输入内容"
          disabled
        ></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item label="联系电话" name="phone">
        <uni-easyinput
          v-model="formData.phone"
          placeholder="请输入内容"
          maxlength="11"
          @blur="checkPhone"
        ></uni-easyinput>
      </uni-forms-item>
      <uni-forms-item label="备注" name="remark">
        <uni-easyinput
          v-model="formData.remark"
          placeholder="请输入内容"
          maxlength="200"
        ></uni-easyinput>
      </uni-forms-item>
      <uni-section title="工器具退料" type="line"></uni-section>
      <eselect
        v-model="equipmentId"
        style="width: 100%; height: 90rpx; margin: 10px 0"
        ref="treeSelect"
        :options="equipmentList"
        :disabled="!formData.teamId || !formData.projectId"
        @change="changeEquipment"
      ></eselect>
    </uni-forms>

    <uni-table ref="table" border stripe emptyText="暂无更多数据">
      <uni-tr>
        <uni-th width="60" align="center">序号</uni-th>
        <uni-th width="140" align="center">类型名称</uni-th>
        <uni-th width="140" align="center">规格型号</uni-th>
        <uni-th width="80" align="center">在用数</uni-th>
        <uni-th width="120" align="center">退料数</uni-th>
        <uni-th width="120" align="center">损坏价值判定</uni-th>
        <uni-th width="90" align="center">操作</uni-th>
      </uni-tr>
      <uni-tr v-for="(item, index) in tableData" :key="index">
        <uni-td align="center">{{ index + 1 }}</uni-td>
        <uni-td align="center">{{ item.maTypeName }}</uni-td>
        <uni-td align="center">
          <view class="name">{{ item.typeName }}</view>
        </uni-td>
        <uni-td align="center">{{ item.num }}</uni-td>
        <uni-td align="center">
          <uni-easyinput
            v-if="item.manageType == 1"
            v-model="item.preNum"
            placeholder="请输入数量"
            type="number"
            @blur="checkPerNum(item)"
          ></uni-easyinput>
          <!-- 编码 -->
          <span v-else style="color: #409eff" @click="getCode(item)">{{
            item.maCodeList.length == 0 ? '选择编码' : item.maCodeList.length
          }}</span>
        </uni-td>
        <uni-td align="center"
          ><uni-easyinput v-model="item.apDetection" placeholder="请输入内容"></uni-easyinput
        ></uni-td>
        <uni-td align="center">
          <button
            class="uni-button"
            size="mini"
            type="warn"
            @click="
              () => {
                tableData.splice(index, 1)
              }
            "
          >
            删除
          </button>
        </uni-td>
      </uni-tr>
    </uni-table>

    <button style="width: 100%; margin: 50px 0" type="primary" @click="submit(1)">确 定</button>
  </div>
</template>

<script setup>
import { onLoad, onShow, onBackPress } from '@dcloudio/uni-app'
import { ref, reactive } from 'vue'
import eselect from '@/components/tree-select/eselect.vue'
import {
  getBmTeamList,
  getProjectList,
  backTask,
  editBackTask,
  getAgreementInfoById,
  detailsBackTask,
  getUseTypeTree,
} from '@/services/materialsStation'

const title = ref('工器具退料申请')
const opts = ref({})
const form = ref()
const formData = reactive({
  teamId: undefined,
  projectId: '',
  backPerson: '',
  phone: '',
  agreementId: undefined,
  remark: undefined,
  isBack: 1,
  remark: '',
})
const agreementId = ref('')
const equipmentId = ref()
const teamRange = ref([]) // 班组
const prodRange = ref([]) // 工程
const equipmentList = ref([]) // 工器具
const rules = {
  teamId: {
    rules: [{ required: true, errorMessage: '请选择班组' }],
  },
  projectId: {
    rules: [{ required: true, errorMessage: '请选择工程' }],
  },
  backPerson: {
    rules: [{ required: true, errorMessage: '请填写退料人' }],
  },
}
const tableData = ref([])

// 编辑获取详情
const getDetailsById = async () => {
  try {
    const res = await detailsBackTask(opts.value.id)
    console.log('🚀 ~ getDetailsById ~ res:', res)
    res.data.backApplyInfo.projectId = res.data.backApplyInfo.proId
    if (res.data && res.data.backApplyDetailsList && res.data.backApplyDetailsList.length > 0) {
      tableData.value = res.data.backApplyDetailsList.map((item) => {
        return {
          ...item,
          maTypeName: item.materialName, // 显示类型名称
        }
      })
    }
    Object.assign(formData, res.data.backApplyInfo)
    console.log('🚀 ~ getDetailsById ~ formData:', formData)
    getAgreement()
  } catch (error) {
    console.log('🚀 ~ getDetailsById ~ error:', error)
  }
}
// 获取班组
const getTeamList = async () => {
  try {
    const res = await getBmTeamList({ isAll: 0 })
    // teamRange.value = res.data
    if (res.data.length > 0) {
      teamRange.value = res.data.map((item) => {
        return {
          ...item,
          value: item.id,
          text: item.teamName,
        }
      })
      getProjectListApi()
    }
  } catch (error) {
    console.log('🚀 ~ getTeamList ~ error:', error)
  }
}
// 获取工程
const getProjectListApi = async () => {
  console.log('🚀 ~ 工程')
  try {
    const res = await getProjectList({ unitId: null, isApp: true, teamName: formData.teamName })
    if (!res.data || !res.data.length) return
    console.log('🚀 ~ getProjectListApi ~ res:', res)
    prodRange.value = res.data.map((item) => {
      return {
        ...item,
        value: item.proId,
        text: item.proName,
      }
    })
  } catch (error) {
    console.log('🚀 ~ getProjectListApi ~ error:', error)
  }
}
//协议
const getAgreement = () => {
  console.log(formData.teamId, formData.projectId)
  let obj = {
    teamId: formData.teamId,
    projectId: formData.projectId,
  }
  getAgreementInfoById(obj)
    .then((res) => {
      console.log(res)
      if (res.code == 200) {
        agreementId.value = res.data.agreementId
        formData.agreementId = res.data.agreementId
        getEquipmentList()
      } else {
        agreementId.value = ''
        formData.agreementId = ''
      }
    })
    .catch((error) => {
      formData.agreementId = ''
      console.log(error)
    })
}
// 获取工具器
const getEquipmentList = async () => {
  try {
    let obj = {
      agreementId: agreementId.value,
    }
    const res = await getUseTypeTree(obj)
    // machineList.value = res.data
    if (res.data.length > 0) {
      equipmentList.value = formatEquipmentTree(res.data)
      console.log('🚀 ~ getEquipmentList ~ machineList.value:', equipmentList.value)
    }
  } catch (error) {
    console.log('🚀 ~ getMachineListApi ~ error:', error)
  }
}
function formatEquipmentTree(list) {
  return list.map((item) => {
    const newItem = {
      ...item,
      id: item.typeId,
      name: item.typeName,
    }
    if (item.children && item.children.length > 0) {
      newItem.children = formatEquipmentTree(item.children)
    }
    return newItem
  })
}
// 校验电话
const checkPhone = (rule, value, callback) => {
  // if (!formData.phone) {
  //   uni.showToast({
  //     icon: 'none',
  //     title: '请输入电话号码',
  //   })
  //   return false
  // }
  if (!/^1[3-9][0-9]{9}$/.test(formData.phone)) {
    uni.showToast({
      icon: 'none',
      title: '请输入正确的电话号码',
    })
    // 清空
    formData.phone = ''
    return false
  }
  return true
}

// 检查数量
const checkPerNum = (item) => {
  // 大于1的正整数 正则校验
  if (!/^[1-9]\d*$/.test(item.preNum)) {
    uni.showToast({
      icon: 'none',
      title: '请输入正确的数量',
    })
    // 重置为1
    item.preNum = 1
    return false
  }
}
// 选择班组
const changeTeamd = (e) => {
  console.log('🚀 ~ changeTeamd ~ e:', e)
  const team = teamRange.value.find((item) => item.id === e)
  console.log('🚀 ~ changeTeamd ~ team:', team)
  formData.projectId = null
  formData.teamName = team ? team.teamName : ''
  formData.backPerson = team ? team.relName : ''
  formData.phone = team ? team.relPhone : ''
  formData.teamId = e
  getProjectListApi()
}
// 选择工程
const changeProd = (e) => {
  console.log('🚀 ~ changeProd ~ e:', e)
  formData.projectId = e
  getAgreement()
}
// 选择工器具
const changeEquipment = (e) => {
  console.log('🚀 ~ changeEquipment ~ e:', e)
  if (tableData.value.some((item) => item.typeId === e.typeId)) {
    uni.showToast({
      icon: 'none',
      title: '该型号已添加',
    })
    return
  }

  // 从 equipmentList.value 中获取点击id的上一级的 typeName
  const equipment = findEquipmentById(equipmentList.value, e.parentId)
  tableData.value.push({
    ...JSON.parse(JSON.stringify(e)),
    maTypeName: equipment.typeName,
    preNum: e.manageType == '1' ? 1 : 0, // 如果是数量设备，默认退料数为1
    maCodeList: [],
  })
  setTimeout(() => {
    equipmentId.value = ''
  }, 300)
}
// 递归查找指定 id 的节点
function findEquipmentById(list, id) {
  for (const item of list) {
    if (item.id === id) {
      return item
    }
    if (item.children && item.children.length > 0) {
      const found = findEquipmentById(item.children, id)
      if (found) return found
    }
  }
  return null
}

// 获取编码
const getCode = (item) => {
  console.log('🚀 ~ getCode ~ item:', item)
  if (item.maCodeList.length > 0) {
    item.maCodeList.forEach((code) => {
      code.checked = true
    })
  }
  item.isEdit = opts.value.isEdit
  item.isBack = true
  item.teamId = formData.teamId
  item.projectId = formData.projectId
  uni.navigateTo({
    url: '/pages/materialsStation/toolsLease/codeOut?params=' + JSON.stringify(item),
  })
}

const submit = (isBack) => {
  console.log('🚀 ~ submit ~ submit:', formData)
  // 校验表单
  form.value
    .validate()
    .then(async (valid) => {
      formData.isBack = isBack
      formData.createBy = uni.getStorageSync('username') || ''
      console.log('🚀 ~ form.value.validate.then ~ valid:', valid)
      if (tableData.value.length === 0) {
        await uni.showToast({
          title: '请添加退料数据',
          icon: 'none',
          duration: 1000,
        })
        return
      }
      // tableData.value 循环 preNum 不能小于 0, 小于0的提示到具体行
      for (let i = 0; i < tableData.value.length; i++) {
        console.log('🚀 ~ .then ~ tableData.value[i].preNum:', tableData.value[i].preNum)
        if (tableData.value[i].preNum < 1) {
          await uni.showToast({
            title: `第${i + 1}行退料数量不能为0`,
            icon: 'none',
            duration: 1000,
          })
          return
        } else if (tableData.value[i].preNum > tableData.value[i].num) {
          await uni.showToast({
            title: `第${i + 1}行退料数量不能大于在用数量`,
            icon: 'none',
            duration: 1000,
          })
          return
        }
      }

      const res = await uni.showModal({
        title: '提示',
        content: '是否确认提交？',
        confirmText: '确定',
        cancelText: '取消',
      })
      console.log('🚀 ~ .then ~ res:', res)
      if (!res.confirm) return
      tableData.value.forEach((item) => {
        item.outNum = item.preNum
      })
      const params = {
        backApplyDetailsList: tableData.value,
        backApplyInfo: formData,
      }
      console.log('🚀 ~ .then ~ params:', params)
      uni.showLoading({
        title: '提交中...',
      })
      try {
        let res = null
        if (!opts.value.isEdit) {
          console.log('🚀 ~ .then ~ 新增:')
          res = await backTask(params)
        } else {
          console.log('🚀 ~ .then ~ 编辑:')
          res = await editBackTask(params)
        }
        console.log('🚀 ~ .then ~ res:', res)
        tableData.value = []
        uni.hideLoading()
        back()
      } catch (error) {
        console.log('🚀 ~ .then ~ error:', error)
        uni.hideLoading()
      }
    })
    .catch((err) => {
      console.log('🚀 ~ form.value.validate.catch ~ err:', err)
    })
}
const back = () => {
  if (tableData.value.length > 0) {
    uni
      .showModal({
        title: '提示',
        content: '当前有未提交的数据，是否暂存？',
        confirmText: '确定',
        cancelText: '取消',
      })
      .then((res) => {
        if (res.confirm) {
          submit(0)
        } else {
          uni.navigateBack({
            delta: 1,
          })
        }
      })
  } else {
    uni.navigateBack({
      delta: 1,
    })
  }
}

onLoad((opt) => {
  console.log('onLoad', opt)
  opts.value = opt.params ? JSON.parse(opt.params) : {}
  title.value = opts.value.isEdit ? '编辑工器具退料' : '新增工器具退料'
  if (opts.value.isEdit) {
    getDetailsById()
  } else {
    getTeamList()
  }
})
onShow(() => {
  console.log('onShow')
  // 监听添加编码
  uni.$on('maCodeList', (data) => {
    console.log('🚀 ~ onShow ~ data:', data)
    const item = tableData.value.find((item) => item.typeId == data[0].typeId)
    console.log('🚀 ~ onShow ~ item:', item)
    if (item) {
      item.maCodeList = data
      item.preNum = data.length
    }
  })
  console.log('🚀 ~ onShow ~ tableData.value:', tableData.value)
})
onBackPress((opt) => {
  console.log('🚀 ~ onBackPress ~ opt:', opt)
  if (opt.from == 'backbutton') {
    if (tableData.value.length > 0) {
      // 仅提示数据未提交
      uni.showToast({
        title: '当前有未提交数据, 请暂存或提交',
        icon: 'none',
        duration: 1000,
      })
      return true
    }
  } else {
    return false
  }
})
</script>

<style lang="scss" scoped>
.content {
  padding: 10px;
  background-color: #fafafa;
}
.col {
  display: flex;
  align-items: center;
  margin-bottom: 15px;
}
</style>
