<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="800px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
<el-form-item prop="feedingRecordCode">
  <template #label>
    <span>
      {{ t('ProductionPlan.FeedingRecord.dialogCodeLabel') }}
      <el-tooltip :content="t('ProductionPlan.FeedingRecord.dialogCodeTooltip')" placement="top">
        <Icon icon="ep:question-filled" />
      </el-tooltip>
    </span>
  </template>
  <el-row :gutter="10" style="width: 100%;">
    <el-col :xs="24" :sm="18" :md="16" :lg="14" :xl="12">
      <el-input 
        :disabled="formData.isCode == true || formType === 'update'" 
        v-model="formData.feedingRecordCode" 
        :placeholder="t('ProductionPlan.FeedingRecord.dialogCodePlaceholder')"
      />
    </el-col>
    <el-col :xs="24" :sm="6" :md="4" :lg="3" :xl="2">
      <div>
        <el-switch 
          v-model="formData.isCode" 
          :disabled="formType === 'update'"
        />
      </div>
    </el-col>
  </el-row>
</el-form-item>

      <!-- <el-form-item label="制浆线:" prop="feedingPipeline">
          <el-tree-select
                  v-model="formData.feedingPipeline"
                  :data="organizationTree"
                  :props="defaultProps"
                  check-strictly
                  default-expand-all
                  placeholder="请选择制浆线"
                />
      </el-form-item> -->
      <el-form-item prop="feedingType">
        <template #label>
            <span>
              {{ t('ProductionPlan.FeedingRecord.dialogFeedingTypeLabel') }}
              <el-tooltip :content="t('ProductionPlan.FeedingRecord.dialogFeedingTypeTooltip')" placement="top">
                <Icon icon="ep:question-filled" />
              </el-tooltip>
            </span>
        </template>
        <el-radio-group v-model="formData.feedingType">
          <el-radio
            v-for="dict in getStrDictOptions(DICT_TYPE.MES_FEEDING_TYPE)"
            :key="dict.value"
            :label="dict.value"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-form-item :label="t('ProductionPlan.FeedingRecord.dialogPlanLabel')" prop="planId" v-if = "formData.feedingType == 'org'">
            <el-select
              v-model="formData.planId"
              @change="handleQuery(formData.planId)"
              clearable
              filterable
              :placeholder="t('ProductionPlan.FeedingRecord.dialogPlanPlaceholder')"
            >
              <el-option
                v-for="item in planList"
                :key="item.id"
                :label="item.code"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
          <el-form-item :label="t('ProductionPlan.FeedingRecord.dialogPipelineLabel') + ':'" prop="feedingPipeline" v-if = "formData.feedingType != 'org'">
          <el-tree-select
                  v-model="formData.feedingPipeline"
                  :data="organizationTree"
                  :props="defaultProps"
                  check-strictly
                  default-expand-all
                  :placeholder="t('ProductionPlan.FeedingRecord.dialogPipelinePlaceholder')"
                />
      </el-form-item>
      <el-form-item :label="t('ProductionPlan.FeedingRecord.dialogProductLabel')" prop="productId" v-if="formData.feedingType !='org'">
        <el-select
          v-model="formData.productId"
          clearable
          filterable
          :placeholder="t('ProductionPlan.FeedingRecord.dialogProductPlaceholder')"
          class="!w-1/1"
        >
          <el-option
            v-for="item in productList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item  :label="t('ProductionPlan.FeedingRecord.dialogWeightLabel') + ':'" prop="weight" v-if="formData.feedingType !='org'">
        <el-input-number v-model="formData.weight" :min="0" :precision="2" class="!w-1/1" :placeholder="t('ProductionPlan.FeedingRecord.dialogWeightPlaceholder')"
        />
      </el-form-item>
      <el-form-item :label="t('ProductionPlan.FeedingRecord.dialogFeedingTimeLabel') + ':'" prop="feedingTime">
        <el-date-picker
          v-model="formData.feedingTime"
          type="date"
          value-format="x"
          :placeholder="t('ProductionPlan.FeedingRecord.dialogFeedingTimePlaceholder')"
          class="!w-full"
        />
      </el-form-item>
      <el-form-item :label="t('ProductionPlan.FeedingRecord.dialogRemarkLabel') + ':'" prop="remark">
        <el-input v-model="formData.remark" :placeholder="t('ProductionPlan.FeedingRecord.dialogRemarkPlaceholder')" />
      </el-form-item>

    </el-form>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName" v-if="formData.feedingType=='org'">
      <el-tab-pane :label="t('ProductionPlan.FeedingRecord.detailTabFeedingDetailLabel')" name="feedingRecordDetail">
        <!-- <FeedingRecordDetailForm ref="feedingRecordDetailFormRef" :record-id="formData.id" /> -->
           <el-form
    ref="recordFormRef"
    :rules="recordFormRules"
    :model="recordData"
    v-loading="formLoading"
    label-width="0px"
    :inline-message="true"
  >
    <el-table :data="recordData" class="-mt-10px">
      <el-table-column :label="t('ProductionPlan.FeedingRecord.detailTableIndexColumn')" type="index" width="100" />
      <el-table-column :label="t('ProductionPlan.FeedingRecord.detailTableItemColumn')" prop="productName" width="100" />
      <el-table-column :label="t('ProductionPlan.FeedingRecord.detailTableUnitColumn')" prop="unitName" width="100" />
      <el-table-column :label="t('ProductionPlan.FeedingRecord.detailTableWeightColumn')" min-width="150">
        <template #default="{ row, $index }">
          <el-form-item :prop="`${$index}.weight`" :rules="recordFormRules.weight">
            <el-input-number v-model="row.weight" :min="0" :precision="2" class="!w-1/1" placeholder=""
            />
          </el-form-item>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" fixed="right" label="操作" width="60">
        <template #default="{ $index }">
          <el-button @click="handleDelete($index)" link type="danger">
            <Icon icon="ep:delete" />
          </el-button>
        </template>
      </el-table-column> -->
    </el-table>
  </el-form>
      </el-tab-pane>
    </el-tabs>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">{{ t('ProductionPlan.FeedingRecord.dialogSubmitButtonText') }}</el-button>
      <el-button @click="dialogVisible = false">{{ t('ProductionPlan.FeedingRecord.dialogCancelButtonText') }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { FeedingRecordApi, FeedingRecordVO } from '@/api/mes/feedingrecord'
import FeedingRecordDetailForm from './components/FeedingRecordDetailForm.vue'
import {ProductApi, ProductVO} from "@/api/erp/product/product";
import { OrganizationApi, OrganizationVO } from '@/api/mes/organization'
import { defaultProps, handleTree } from '@/utils/tree'
import {PlanApi, PlanVO} from "@/api/mes/plan";
const planList = ref<PlanVO[]>([]) // 列表

/** 投料记录 表单 */
defineOptions({ name: 'FeedingRecordForm' })

import { ItemRequisitionApi } from '@/api/mes/itemrequisition'
const organizationTree = ref() // 树形结构
const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const productList = ref<ProductVO[]>([]) // 产品列表
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  feedingRecordCode: undefined,
  productId: undefined,
  planId: undefined,
  itemId: undefined,
  feedingPipeline: undefined,
  feedingType: undefined,
  weight: undefined,
  feedingTime: undefined,
  userId: undefined,
  remark: undefined,
  recordStatus: undefined,
  isCode: undefined
})
const formRules = reactive({
  feedingType: [{ required: true, message: t('ProductionPlan.FeedingRecord.validatorFeedingTypeRequired'), trigger: 'blur' }],
  feedingPipeline: [{ required: true, message: t('ProductionPlan.FeedingRecord.validatorPipelineRequired'), trigger: 'blur' }],
  planId: [{ required: true, message: t('ProductionPlan.FeedingRecord.validatorPlanRequired'), trigger: 'change' }]
})
const recordFormRules = reactive({
  weight: [{ required: true, message: t('ProductionPlan.FeedingRecord.validatorDetailWeightRequired'), trigger: 'blur' }]
})
const formRef = ref() // 表单 Ref

const list = ref([]) // 列表的数据

const recordData = ref([])

/** 子表的表单 */
const subTabsName = ref('feedingRecordDetail')
const recordFormRef = ref()

/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  formData.value.feedingType = 'org'
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await FeedingRecordApi.getFeedingRecord(id)
    } finally {
      formLoading.value = false
    }
  }
  // 加载产品、
  productList.value = await ProductApi.getMesProductSimpleList()
  // 加载组织
  await getOrganizationTree()
  planList.value = await PlanApi.getPlanByStatus(1)
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  if(formData.value.feedingType == 'org'){
    // 校验子表单
    try {
      await recordFormRef.value.validate()
    } catch (e) {
      subTabsName.value = 'feedingRecordDetail'
      return
    }
  }
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value as unknown as FeedingRecordVO
    // 拼接子表的数据
    if(formData.value.feedingType == 'org'){
      //data.feedingRecordDetails = feedingRecordDetailFormRef.value.getData()
      data.feedingRecordDetails = recordData.value
      console.log(data.feedingRecordDetails)
    }
    if (formType.value === 'create') {
      await FeedingRecordApi.createFeedingRecord(data)
      message.success(t('common.createSuccess'))
    } else {
      await FeedingRecordApi.updateFeedingRecord(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    feedingRecordCode: undefined,
    productId: undefined,
    planId: undefined,
    itemId: undefined,
    feedingPipeline: undefined,
    feedingType: undefined,
    weight: undefined,
    feedingTime: undefined,
    userId: undefined,
    remark: undefined,
    recordStatus: undefined,
    isCode: true
  }
  recordData.value = []
  formRef.value?.resetFields()
}

/** 获得产线工位树 */
const getOrganizationTree = async () => {
  organizationTree.value = []
  const req = {orgClass:'pipeline'}
  const data = await OrganizationApi.getOrganizationList(req)
  const root: Tree = { id: 0, name: '顶级组织', children: [] }
  root.children = handleTree(data, 'id', 'parentId')
  organizationTree.value.push(root)
}

const data = ref({
  requisitionId : undefined
})
const to = ref(0) // 列表的总页数
const handleQuery = async(planId : number) => {
  data.value = await PlanApi.getPlan(planId)
  //console.log(data.value)
  list.value = await ItemRequisitionApi.getItemRequisitionDetailListByItemRequisitionId(data.value.requisitionId)
  recordData.value = list.value
  to.value = list.total
}
</script>
