<template>
  <div>
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="80%" :close-on-click-modal="false">
      <el-card style="margin-bottom: 20px">
        <el-form
          v-if="dialogVisible"
          ref="dialogForm"
          :model="dialogForm"
          :rules="rules"
          size="small"
          inline
          @submit.native.prevent
        >
          <el-form-item label="规格型号">
            <el-cascader
              v-model="typeIdList"
              :options="options"
              :props="{ value: 'typeId', label: 'typeName' }"
              clearable
              @change="handleChange"
              style="width: 400px"
            />
          </el-form-item>
          <!-- 厂家 -->
          <el-form-item label="生产厂家">
            <el-select v-model="dialogForm.supplierId" placeholder="请选择厂家" clearable style="width: 240px">
              <el-option
                v-for="item in manufacturerSelect"
                :key="item.id"
                :label="item.label"
                :value="item.id"
              ></el-option>
            </el-select>
          </el-form-item>
          <!-- 出厂日期 -->
          <el-form-item label="出厂日期">
            <el-date-picker
              v-model="dialogForm.productionDate"
              type="date"
              clearable
              placeholder="选择出厂日期"
              value-format="yyyy-MM-dd"
              style="width: 240px"
            />
          </el-form-item>
          <!-- 申请数量 -->
          <el-form-item label="申请数量" prop="applyNum">
            <el-input-number
              v-model="dialogForm.applyNum"
              :min="1"
              :max="9999"
              :controls="false"
              placeholder="请输入申请数量"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item style="display: flex; justify-content: flex-end">
            <el-button type="primary" icon="el-icon-plus" :disabled="typeIdList.length == 0" @click="handleAdd"
              >点击填充</el-button
            >
          </el-form-item>
        </el-form>
      </el-card>

      <el-card v-loading="isLoading">
        <el-row :gutter="10" class="mb8" justify="end">
          <el-col :span="24" style="display: flex; justify-content: flex-end">
            <el-button type="primary" :disabled="dialogList.length == 0" @click="submit">确定</el-button>
          </el-col>
        </el-row>
        <el-table :data="dialogList" border stripe highlight-current-row :max-height="500" style="width: 100%">
          <el-table-column type="index" width="55" label="序号" align="center" />
          <el-table-column
            v-for="(column, index) in dialogColumns"
            :width="column.width"
            :show-overflow-tooltip="!column.unShowTooltip"
            :key="index"
            :label="column.label"
            :prop="column.prop"
            align="center"
          >
            <!-- 插槽 -->
            <template v-slot="{ row }" v-if="column.prop == 'supplierId'">
              <el-select v-model="row.supplierId" placeholder="请选择厂家" style="width: 150px">
                <el-option
                  v-for="item in manufacturerSelect"
                  :key="item.id"
                  :label="item.label"
                  :value="item.id"
                ></el-option>
              </el-select>
            </template>
            <template v-slot="{ row }" v-else-if="column.prop == 'productionDate'">
              <el-date-picker
                v-model="row.productionDate"
                type="date"
                clearable
                placeholder="选择出厂日期"
                value-format="yyyy-MM-dd"
                style="width: 150px"
              />
            </template>
            <!-- 插槽 -->
            <template v-slot="{ row }" v-else-if="column.prop == 'toolPrice'">
              <el-input-number v-model="row.toolPrice" :min="0" :max="99999999" :controls="false" style="width: 120px" />
            </template>
            <!-- 插槽 -->
            <template v-slot="{ row }" v-else-if="column.prop == 'identifyCode'">
              <el-input v-model="row.identifyCode" maxlength="999" style="width: 120px" />
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center">
            <template slot-scope="{ row, $index }">
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete($index)" style="color: red"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-card>
    </el-dialog>
  </div>
</template>

<script>
import { getTreeSelectApi, addApplyCodeApi, addToolApi } from '@/api/toolsManage'
import { getManufacturerSelectApi } from '@/api/EquipmentLedger'

export default {
  data() {
    return {
      isLoading: false,
      dialogTitle: '新增编码工具',
      dialogVisible: false,
      dialogForm: {
        applyId: null,
        typeId: null,
        supplierId: null,
        supplierName: null,
        productionDate: null,
        applyNum: 1,
      },
      rules: {
        applyNum: [{ required: true, message: '请输入申请数量', trigger: 'blur' }],
      },
      typeIdList: [],
      dialogColumns: [
        { label: '工具专业', prop: 'fourthParentName' },
        { label: '施工类型', prop: 'greatGrandparentName' },
        { label: '工具类型', prop: 'grandparentTypeName' },
        { label: '工具名称', prop: 'parentTypeName' },
        { label: '规格型号', prop: 'typeName' },
        { label: '计量单位', prop: 'unitName' },
        { label: '生产厂家', prop: 'supplierId', width: 180 },
        { label: '出厂日期', prop: 'productionDate', width: 180 },
        { label: '资产原值', prop: 'toolPrice', width: 150 },
        { label: '原始编码', prop: 'identifyCode', width: 150 },
      ],
      dialogList: [],
      options: [],
      activeLabels: [],
      lastNode: null,
      manufacturerSelect: [],
    }
  },
  methods: {
    openDialog(applyId) {
      this.dialogForm.applyId = applyId
      this.typeIdList = []
      this.dialogList = []
      this.dialogVisible = true
      this.getTreeSelect()
      this.getManufacturerSelect()
    },
    async getTreeSelect() {
      try {
        const res = await getTreeSelectApi({ manageType: 0 })
        this.options = res.data
        this.handleTree(this.options)
      } catch (error) {}
    },
    handleTree(tree) {
      for (const node of tree) {
        if (node.level === '5') {
          // 删除 children
          delete node.children
        } else if (node.children && node.children.length > 0) {
          // 继续递归下级
          this.handleTree(node.children)
        }
      }
    },
    handleChange(val) {
      this.dialogForm.typeId = val ? val[val.length - 1] : ''
      this.activeLabels = this.getLabelsFromValuePath(val, this.options)
      this.lastNode = this.findNodeById(this.options, val[val.length - 1])
      console.log('选中的 labels:', this.activeLabels)
    },
    getLabelsFromValuePath(valuePath, options) {
      let labels = []
      let currentLevel = options

      for (const val of valuePath) {
        const node = currentLevel.find((item) => item.typeId === val)
        if (node) {
          labels.push(node.typeName)
          currentLevel = node.children || []
        } else {
          break
        }
      }
      return labels
    },
    findNodeById(tree, id) {
      for (const node of tree) {
        if (node.typeId === id) return node // 找到了就返回
        if (node.children) {
          const result = this.findNodeById(node.children, id)
          if (result) return result // 子节点中找到了
        }
      }
      return null // 没找到
    },
    handleAdd() {
      const typeId = this.typeIdList[this.typeIdList.length - 1]

      for (let i = 0; i < this.dialogForm.applyNum; i++) {
        this.dialogList.unshift({
          applyId: this.dialogForm.applyId,
          typeId,
          fourthParentName: this.activeLabels[0],
          greatGrandparentName: this.activeLabels[1],
          grandparentTypeName: this.activeLabels[2],
          parentTypeName: this.activeLabels[3],
          typeName: this.activeLabels[4],
          unitName: this.lastNode.unitName,
          applyNum: 1,
          supplierId: this.dialogForm.supplierId,
          supplierName: this.dialogForm.supplierName,
          productionDate: this.dialogForm.productionDate,
          toolPrice: null,
          identifyCode: null,
        })
      }
    },
    handleDelete(index) {
      this.dialogList.splice(index, 1)
      this.$message({
        type: 'success',
        message: '删除成功!',
      })
    },
    // 获取厂家
    async getManufacturerSelect() {
      try {
        const res = await getManufacturerSelectApi()
        this.manufacturerSelect = res.data
      } catch (error) {}
    },
    // 提交
    async submit() {
      try {
        this.isLoading = true
        if (!this.dialogForm.applyId) {
          const res = await addApplyCodeApi()
          this.dialogForm.applyId = res.data.id
          this.dialogList.forEach((item) => {
            item.applyId = res.data.id
          })
        }
        await addToolApi(this.dialogList)
        this.$message({
          type: 'success',
          message: '操作成功!',
        })
        this.dialogVisible = false
        this.$emit('getList', { applyId: this.dialogForm.applyId })
      } catch (error) {
      } finally {
        this.isLoading = false
      }
    },
  },
}
</script>

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