<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1200px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="100px"
      v-loading="formLoading"
    >
      <el-row>
        <el-col :span="8">
          <el-form-item label="工序" prop="orgType">
            <el-select
              :disabled="isDisableUpdate"
              v-model="formData.orgType"
              placeholder=""
              clearable
              @change="changeDate"
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.MES_ORG_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <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="选择报工日期"
              @change="changeDate"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <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-row v-if="formData.orgType && formData.groupType && formData.reportDate">
        <el-col :span="8">
          <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="8">
          <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-col :span="8" >
          <el-text v-if="warningInfo" class="mx-1" type="warning">{{warningInfo}}</el-text>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="计件时段" prop="reportTime">
            <el-input v-model="formData.reportTime" placeholder="请输入计件时段" />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="计件时长" prop="totalTime">
            <el-input-number v-model="formData.totalTime" :min="0"  :precision="2" placeholder="请输入时长" class="!w-260px"/>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="formData.remark" placeholder="请输入备注"/>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <!-- 子表的表单 -->
    <el-tabs v-model="subTabsName">
      <el-tab-pane label="生产报工明细" name="produceReportDetail">
        <ProduceReportDetailForm ref="produceReportDetailFormRef" :report-id="formData.id" />
      </el-tab-pane>
    </el-tabs>
    <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, getStrDictOptions, DICT_TYPE } from '@/utils/dict'
import { ProduceReportApi, ProduceReportVO } from '@/api/mes/producereport'
import ProduceReportDetailForm from './ProduceReportDetailForm.vue'
import {useUserStore} from "@/store/modules/user";
import {OrgWorkerApi, OrgWorkerVO} from "@/api/mes/orgworker";
import {formatToDateTime} from "@/utils/dateUtil";
import * as UserApi from "@/api/system/user";
import {WorkTeamApi} from "@/api/mes/workteam";

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

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const userStore = useUserStore()
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref({
  id: undefined,
  processInstanceId: undefined,
  reportCode: undefined,
  userId: undefined,
  orgId: undefined,
  orgType: undefined,
  reportTime: undefined,
  totalTime: undefined,
  reportStatus: undefined,
  remark: undefined,
  groupType: undefined,
  reportType: undefined,
  reportDateString: undefined,
  reportDate: 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 subTabsName = ref('produceReportDetail')
const produceReportDetailFormRef = ref()

/** 打开弹窗 */
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.userId = userStore.getUser.id
  formData.value.reportType = "代报工"
  warningInfo.value = ''
  isDisableUpdate.value = false

  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      userList.value = await UserApi.getSimpleUserList()
      formData.value = await ProduceReportApi.getProduceReport(id)
      formData.value.reportDate = formatToDateTime(new Date(formData.value.reportDate))
      orgWorkerList.value = await OrgWorkerApi.getOrgWorkerListByOrgId(formData.value.orgId)
      let orgId = formData.value.orgId
      formData.value.orgId = 15
      formData.value.orgId = orgId
    } finally {
      formLoading.value = false
    }
    isDisableUpdate.value=true;
  }
  else{
    await changeDate()
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 校验子表单
  try {
    await produceReportDetailFormRef.value.validate()
  } catch (e) {
    subTabsName.value = 'produceReportDetail'
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    formData.value.reportDateString =  formData.value.reportDate
    const data = formData.value as unknown as ProduceReportVO
    // 拼接子表的数据
    data.produceReportDetails = produceReportDetailFormRef.value.getData()
    if (formType.value === 'create') {
      await ProduceReportApi.createProduceReport(data)
      message.success(t('common.createSuccess'))
    } else {
      await ProduceReportApi.updateProduceReport(data)
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    processInstanceId: undefined,
    reportCode: undefined,
    userId: undefined,
    orgId: undefined,
    orgType: undefined,
    reportTime: undefined,
    totalTime: undefined,
    reportStatus: undefined,
    remark: undefined,
    groupType: undefined,
    reportType: undefined,
    reportDate: undefined
  }
  formRef.value?.resetFields()
}


const warningInfo  = ref()
const orgWorkerList = ref<OrgWorkerVO[]>([]) // 用户列表
const userList = ref<UserApi.UserVO[]>([]) // 用户列表
//更改报工日期时查询用户在该日期绑定的工位信息
const changeDate = async () =>{
  if(formData.value.reportDate && formData.value.groupType && formData.value.orgType){
    formData.value.userId = 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
      if(!formData.value.orgId)
        await changeDateUser()
    }
    if(!formData.value.userId){
      warningInfo.value = '该条件下未查询到工人安排信息！'
      message.error(warningInfo.value)
    }
  }
}
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 changeDateUser = async () =>{
  orgWorkerList.value = null
  if(formData.value.reportDate && formData.value.groupType && formData.value.orgType && formData.value.userId){
    formData.value.orgId = null
    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.orgId){
      warningInfo.value = '该条件下未查询到工位安排信息！'
      message.error(warningInfo.value)
    }
  }
}

</script>
