<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="日期" prop="reportDate">
            <el-date-picker
              :disabled="isDisableUpdate"
              v-model="formData.reportDate"
              type="date"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="选择日期"
              :default-value="new Date()"
              @change="changeDate"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="班别" prop="groupType">
            <el-radio-group v-model="formData.groupType">
              <el-radio
                :disabled="isDisableUpdate"
                v-for="dict in getIntDictOptions(DICT_TYPE.MES_GROUP_TYPE)"
                :key="dict.value"
                :label="dict.value"
                @change="changeDate"
              >
                {{ dict.label }}
              </el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="类型" prop="orgType">
        <el-radio-group v-model="formData.orgType">
          <el-radio
            :disabled="isDisableUpdate"
            v-for="dict in getStrDictOptions(DICT_TYPE.MES_ORG_TYPE)"
            :key="dict.value"
            :label="dict.value"
            @change="changeDate"
          >
            {{ dict.label }}
          </el-radio>
        </el-radio-group>
      </el-form-item>
      <el-row v-if="formData.orgType && formData.groupType && formData.reportDate">
        <el-col :span="12">
          <el-form-item label="工人" prop="userId">
            <el-select
              :disabled="isDisableUpdate"
              v-model="formData.userId"
              clearable
              filterable
              @change="changeDateUser"
              placeholder="请选择工人"
            >
              <el-option
                v-for="item in userList"
                :key="item.id"
                :label="item.nickname"
                :value="item.id"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="工位" prop="orgId">
            <el-select
              :disabled="isDisableUpdate"
              v-model="formData.orgId"
              clearable
              filterable
              placeholder="请选择工位"
            >
              <el-option
                v-for="item in orgWorkerList"
                :key="item.orgId"
                :label="item.orgName"
                :value="item.orgId"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-text v-if="warningInfo" class="mx-1" type="warning">{{warningInfo}}</el-text>
      <el-divider />
      <el-form-item label="产品" prop="productId">
        <el-select v-model="formData.productId"  clearable filterable placeholder="请选择" >
          <el-option
            v-for="item in productList"
            :key="item.id"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>

      <el-row>
        <el-col :span="12">
          <el-form-item label="成品数量" prop="qualityNumber">
            <el-input-number v-model="formData.qualityNumber" :min="0" @change="numberChange"  placeholder="请输入数量"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="废品数量" prop="wasteNumber">
            <el-input-number v-model="formData.wasteNumber" :min="0"  @change="numberChange" placeholder="请输入"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="12">
          <el-form-item  label="总数量" prop="totalNumber">
            <el-input-number disabled v-model="formData.totalNumber" :min="0"  placeholder="请输入数量"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="成品率%" prop="qualityRate">
            <el-input-number disabled v-model="formData.qualityRate" :min="0"  :precision="2" placeholder="请输入数量"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="废品原因" prop="wasteReason">
        <el-input v-model="formData.wasteReason" placeholder="请输入废品原因" />
      </el-form-item>
      <el-form-item label="打包数量" prop="packageNumber">
        <el-input-number v-model="formData.packageNumber" :min="0"  placeholder="请输入数量"/>
      </el-form-item>
      <el-row>
        <el-col :span="12">
          <el-form-item label="总时长/小时" prop="totalTime">
            <el-input-number v-model="formData.totalTime" :min="0"  :precision="2" placeholder="请输入数量"/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="计件时长" prop="reportTime">
            <el-input-number v-model="formData.reportTime" :min="0"  :precision="2" placeholder="请输入数量"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="备注" prop="remark">
        <el-input v-model="formData.remark" placeholder="请输入备注" />
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import {getIntDictOptions, DICT_TYPE, getBoolDictOptions, getStrDictOptions} from '@/utils/dict'
import { ProduceReportDetailApi, ProduceReportDetailVO } from '@/api/mes/producereport'
import {defaultProps, handleTree} from "@/utils/tree";
import {OrganizationApi, OrganizationVO} from "@/api/mes/organization";
import * as UserApi from "@/api/system/user";
import {ProductApi, ProductVO} from "@/api/erp/product/product";
import {OrgWorkerApi, OrgWorkerVO} from "@/api/mes/orgworker";
import {PlanApi} from "@/api/mes/plan";
import {formatToDate, formatToDateTime} from "@/utils/dateUtil";
import {WorkTeamApi} from "@/api/mes/workteam";

/** 生产报工明细 表单 */
defineOptions({ name: 'ProduceReportDetailForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const userList = ref<UserApi.UserVO[]>([]) // 用户列表
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,
  reportId: undefined,
  planId: undefined,
  productId: undefined,
  userId: undefined,
  orgId: undefined,
  orgType: undefined,
  groupType: undefined,
  qualityRate: undefined,
  wasteReason: undefined,
  totalTime: undefined,
  packageNumber: undefined,
  remark: undefined,
  isEnable: undefined,
  qualityNumber: undefined,
  wasteNumber: undefined,
  totalNumber: undefined,
  reportDate: undefined,
  reportTime: undefined,
  reportStatus: undefined,
  reportDateString: undefined,
  reportType: undefined
})
const formRules = reactive({
  reportDate: [{ required: true, message: '日期不能为空', trigger: 'blur' }],
  groupType: [{ required: true, message: '班别不能为空', trigger: 'blur' }],
  productId: [{ required: true, message: '产品不能为空', trigger: 'blur' }],
  userId: [{ required: true, message: '工人不能为空', trigger: 'blur' }],
  orgId: [{ required: true, message: '工位不能为空', trigger: 'blur' }],
  orgType: [{ required: true, message: '工序不能为空', trigger: 'blur' }],
})
const formRef = ref() // 表单 Ref

const isDisableUpdate = ref(false)
/** 打开弹窗 */
const open = async (type: string, id?: number) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  formData.value.reportDate = getCurrentDate()
  formData.value.groupType = 1
  formData.value.orgType = 'zhijiang'
  warningInfo.value = ''
  isDisableUpdate.value = false
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      formData.value = await ProduceReportDetailApi.getProduceReportDetail(id)
      formData.value.reportDate = formatToDateTime(new Date(formData.value.reportDate))
    } finally {
      formLoading.value = false
    }
    isDisableUpdate.value=true;
  }
  await changeDate()

  productList.value = await PlanApi.getStartAndFinishPlanProduct()
  if(productList.value.length ==1)
    formData.value.productId = productList.value[0].id
  if(type === 'replace'){
    dialogTitle.value = "代报工"
    formData.value.reportType = '代报工'
  }
  else if(type === 'update'){
    dialogTitle.value = "编辑代报工"
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async (reportType?:string) => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    formData.value.reportDateString =  formData.value.reportDate
    const data = formData.value as unknown as ProduceReportDetailVO
    if (formType.value === 'replace') {
      await ProduceReportDetailApi.createProduceReportDetail(data)
      message.success(t('common.createSuccess'))
    } else {
      await ProduceReportDetailApi.updateProduceReportDetail(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    reportId: undefined,
    planId: undefined,
    productId: undefined,
    userId: undefined,
    orgId: undefined,
    qualityRate: 0,
    wasteReason: undefined,
    totalTime: 0,
    packageNumber: 0,
    remark: undefined,
    isEnable: undefined,
    qualityNumber: 0,
    wasteNumber: 0,
    totalNumber: 0,
    reportDate: undefined,
    reportTime: 0,
    reportStatus: undefined,
  }
  formRef.value?.resetFields()
}
const getCurrentDate = () =>{
  let now = new Date();
  let year = now.getFullYear();
  let month = now.getMonth() + 1;
  if(month<10){month = '0'+month}
  let day = now.getDate();
  if(day<10)day = '0'+day;
  return year + "-" + month + "-" + day +" 00:00:00";
}

const warningInfo  = ref()
const orgWorkerList = ref<OrgWorkerVO[]>([]) // 用户列表
//更改报工日期时查询用户在该日期绑定的工位信息
const changeDate = async () =>{
  if(formData.value.reportDate && formData.value.groupType && formData.value.orgType){
    formData.value.userId = null
    formData.value.orgId = null
    userList.value = await WorkTeamApi.getUserList(formData.value.orgType, formData.value.groupType)
    if(userList.value && userList.value.length>0){
      formData.value.userId = userList.value[0].id
      orgWorkerList.value = await OrgWorkerApi.getOrgWorkerList2(formData.value)
      if(orgWorkerList.value && orgWorkerList.value.length>0){
        formData.value.orgId = orgWorkerList.value[0].orgId
        warningInfo.value=''
      }
    }
    if(!formData.value.userId || !formData.value.orgId){
      warningInfo.value = '该条件下未查询到工位安排信息！'
      message.error(warningInfo.value)
    }
  }
}
//更改报工日期时查询用户在该日期绑定的工位信息
const changeDateUser = async () =>{
  if(formData.value.reportDate && formData.value.groupType
    && formData.value.orgType &&formData.value.userId){
    orgWorkerList.value = await OrgWorkerApi.getOrgWorkerList2(formData.value)
    if(orgWorkerList.value && orgWorkerList.value.length>0){
      formData.value.orgId = orgWorkerList.value[0].orgId
      warningInfo.value=''
    }
   else {
      warningInfo.value = '该条件下未查询到工位安排信息！'
      message.error(warningInfo.value)
    }
  }
}
const numberChange = async () =>{
  formData.value.totalNumber = formData.value.qualityNumber+formData.value.wasteNumber
  formData.value.qualityRate = formData.value.qualityNumber/formData.value.totalNumber * 100
}
</script>
