<script setup lang="ts">
import { ElMessage } from 'element-plus'
import { ref, reactive, nextTick } from 'vue'
import { GlobalStore } from '@/stores/index'
import PurchaseDetail from './PurchaseDetail.vue'
import Drawer from '@/components/Drawer/index.vue'
import type { FormInstance, FormRules } from 'element-plus'
import { Purchase_Get, Purchase_Edit, Purchase_Add } from '@/api/purchase/index'
import receiveUser from '@/views/storehouse/outStock/receiveUser.vue'
import { deptOptions } from '@/hooks/useTablePublic'

const typeTip = ref('')
const formLabelWidth = ref('120px')
const globalStore = GlobalStore()
const User_tokey = globalStore.GET_User_tokey
const ruleFormRef = ref<FormInstance>()
const drawerRef = ref<InstanceType<typeof Drawer> | null>(null)
const purchaseDetailRef = ref<InstanceType<typeof PurchaseDetail> | null>(null)
const userDrawerRef = ref<InstanceType<typeof receiveUser> | null>(null)
const approverDrawerRef = ref<InstanceType<typeof receiveUser> | null>(null)

const form = ref({
  Id: '',
  T_date: '',
  T_dept: '',
  T_uuid: '',
  T_uuid_name: '',
  T_detail: '',
  T_remark: '',
  T_State: '',
  T_approver: '',
  T_approver_name: '',
  T_product_name: '',
  T_product_quantity: '',
  T_total_price: '',
})

const rules = reactive<FormRules>({
  T_date: [{ required: true, message: '请选择申请日期', trigger: 'change' }],
  T_dept: [{ required: true, message: '请选择申请部门', trigger: 'change' }],
  T_uuid_name: [{ required: true, message: '请选择申请人', trigger: 'blur' }],
  T_approver_name: [{ required: true, message: '请选择审批人', trigger: 'blur' }]
})
const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.resetFields()
}
const callbackDrawer = (done: () => void) => {
  resetForm(ruleFormRef.value)
  purchaseDetailRef.value?.clearDetail()
  done()
}
const addPurchase = (formEl: FormInstance | undefined) => {
  if (!formEl) return
  formEl.validate(async valid => {
    if (valid) {
      let res: any = ''
      // 获取采购明细数据
      const detailData = purchaseDetailRef.value?.getDetailInfo() || []
      // 构建符合后端要求的数据格式
      const formattedDetail = detailData.map((item: any) => ({
        T_name: item.T_name,
        T_bit_number: item.T_bit_number,
        T_packaging: item.T_packaging,
        T_model: item.T_model,
        T_spec: item.T_spec,
        T_quantity: item.T_quantity,
        T_demand: item.T_demand,
        T_unit_price: item.T_unit_price,
        T_amount: item.T_amount,
        T_reference_site: item.T_reference_site,
        T_reference_site_title: item.T_reference_site_title,
        T_remark: item.T_remark,
        T_state: item.T_state,
        T_date: item.T_date
      }))
      // 转换为JSON字符串
      const detail = JSON.stringify(formattedDetail)
      
      const params = {
        User_tokey,
        ...form.value,
        T_detail: detail,
      }
      if (typeTip.value === 'new') {
        res = await Purchase_Add(params)
      } else {
        res = await Purchase_Edit({ ...params, T_id: form.value.Id })
      }

      if (res.Code === 200) {
        ElMessage.success(`采购申请${typeTip.value === 'new' ? '添加' : '修改'}成功!`)
        nextTick(() => {
          emit('onTableList')
          drawerRef.value?.closeDrawer()
          resetForm(ruleFormRef.value)
        })
      }
    }
  })
}

const selectUser = () => userDrawerRef.value?.openDrawer()
const getPurchaseInfo = ({ T_uuid, T_name }: { T_uuid: string; T_name: string }) => {
	form.value.T_uuid = T_uuid
	form.value.T_uuid_name = T_name
}

const selectApprover = () => approverDrawerRef.value?.openDrawer()

const getApproverInfo = ({ T_uuid, T_name }: { T_uuid: string; T_name: string }) => {
	form.value.T_approver = T_uuid
	form.value.T_approver_name = T_name
}

const purchaseFromOpen = (type: string, row?: any) => {
  typeTip.value = type
  nextTick(async () => {
    if (typeTip.value !== 'new') {
      form.value = { ...row }
      // form.value.T_approver = row.T_approver_name
      // form.value.T_uuid = row.T_uuid_name
      const res: any = await Purchase_Get({ T_id: row.Id })
      if (res.Code === 200) {
        // 解析JSON字符串为数组对象
        let detailData = res.Data.T_Detail
        if (typeof detailData === 'string') {
          try {
            detailData = JSON.parse(detailData)
          } catch (error) {
            console.error('JSON解析失败:', error)
            detailData = []
          }
        }
        purchaseDetailRef.value?.setDetailData(detailData || [])
      }
    } else {
      // 新增时设置默认申请日期为当天
      const today = new Date()
      const year = today.getFullYear()
      const month = String(today.getMonth() + 1).padStart(2, '0')
      const day = String(today.getDate()).padStart(2, '0')
      form.value.T_date = `${year}-${month}-${day}`
    }
  })
  drawerRef.value?.openDrawer()
}

const props = defineProps<{ purchaseName: string }>()
const purchaseName = ref(props.purchaseName)

const getTitle = (type: string) => {
  switch (type) {
    case 'new':
      return '新增'
    case 'edit':
      return '编辑'
    default:
      return '详情'
  }
}

const emit = defineEmits<{ (event: 'onTableList'): void }>()



defineExpose({
  purchaseFromOpen
})
</script>
<template>
  <Drawer ref="drawerRef" :handleClose="callbackDrawer" size="90%">
    <template #header="{ params }">
      <h4 :id="params.titleId" :class="params.titleClass">采购申请 - {{ getTitle(typeTip) }}</h4>
    </template>
    <el-form ref="ruleFormRef" :model="form" :rules="rules">

      <el-form-item label="申请日期：" :label-width="formLabelWidth" prop="T_date">
        <el-date-picker
          style="flex: 0 0 50%"
          class="my-date-picker"
          v-model="form.T_date"
		  :disabled="! (typeTip === 'new' || typeTip === 'edit')"
          type="date"
          placeholder="申请日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
		<el-form-item  label="申请部门：" :label-width="formLabelWidth" prop="T_dept">
			<el-select 	:disabled="! (typeTip === 'new' || typeTip === 'edit')" v-model="form.T_dept" class="w-50" clearable placeholder="请选择申请部门">
				<el-option v-for="item in deptOptions" :key="item.id" :label="item.name" :value="item.id"/>
			</el-select>
		</el-form-item>

		<el-form-item  label="申请人：" :label-width="formLabelWidth" prop="T_uuid_name">
			<el-input
				:key="Math.random()"
				v-model="form.T_uuid_name"
				:disabled="! (typeTip === 'new' || typeTip === 'edit')"
				placeholder="请选择申请人"
				class="w-50"
				@focus="selectUser"
			/>
		</el-form-item>
		<el-form-item label="审批人：" :label-width="formLabelWidth" prop="T_approver_name">
			<el-input
				:key="Math.random()"
				:disabled="! (typeTip === 'new' || typeTip === 'edit')"
				v-model="form.T_approver_name"
				autocomplete="off"
				placeholder="审请选择批人"
				class="w-50"
				@focus="selectApprover" />
		</el-form-item>
	<el-form-item v-if="purchaseName !== 'myPurchase'"  label="状态：" :label-width="formLabelWidth" prop="T_state">
		<el-radio-group v-model="form.T_State" :disabled="! (typeTip === 'new' || typeTip === 'edit')">
			<el-radio :label="1">待采购</el-radio>
			<el-radio :label="2">已采购</el-radio>
		</el-radio-group>
	</el-form-item>

	<el-form-item label="产品名称：" :label-width="formLabelWidth" prop="T_product_name">
		<el-input
			v-model="form.T_product_name"
			:disabled="! (typeTip === 'new' || typeTip === 'edit')"
			type="text"
			placeholder="请输入产品名称"
			class="w-50"
		/>
	</el-form-item>

	<el-form-item label="产品数量：" :label-width="formLabelWidth" prop="T_product_quantity">
		<el-input
			v-model="form.T_product_quantity"
			:disabled="! (typeTip === 'new' || typeTip === 'edit')"
			:min="0"
			:precision="0"
			:controls="false"
			placeholder="请输入产品数量"
			class="w-50"
		/>
	</el-form-item>

	<el-form-item label="产品总价：" :label-width="formLabelWidth" prop="T_total_price">
		<el-input
			v-model="form.T_total_price"
			:disabled="! (typeTip === 'new' || typeTip === 'edit')"
			:min="0"
			:precision="2"
			:controls="false"
			placeholder="请输入产品总价"
			class="w-50"
		/>
	</el-form-item>

      <el-form-item label="采购明细：" :label-width="formLabelWidth" prop="T_detail">
        <PurchaseDetail
          ref="purchaseDetailRef"
          :disabled="! (typeTip === 'new' || typeTip === 'edit')"
          :isShow="purchaseName"
          :typeTip="typeTip"
        ></PurchaseDetail>
      </el-form-item>
      <!-- my purchase -->
      <el-form-item label="备注：" :label-width="formLabelWidth" prop="T_remark">
        <el-input
          v-model="form.T_remark"
          :disabled="! (typeTip === 'new' || typeTip === 'edit')"
          :autosize="{ minRows: 4, maxRows: 6 }"
          type="textarea"
          placeholder="请输入备注信息"
        />
      </el-form-item>

      <el-form-item :label-width="formLabelWidth" v-if="purchaseName === 'purchase' || purchaseName === 'myPurchase'">
        <el-button v-if="typeTip === 'new'" class="btn" color="#626aef" @click="addPurchase(ruleFormRef)"
          >提交</el-button
        >
        <el-button v-if="typeTip === 'edit'" class="btn" color="#626aef" @click="addPurchase(ruleFormRef)"
          >修改</el-button
        >
      </el-form-item>
    </el-form>

  </Drawer>
	<receiveUser
		ref="userDrawerRef"
		:key="Math.random()"
		@onUserInfo="getPurchaseInfo"
		title="选择申请人"
	></receiveUser>
	<receiveUser
		:dept_leader="1"
		ref="approverDrawerRef"
		:key="Math.random()"
		@onUserInfo="getApproverInfo"
		title="选择审批人"
	></receiveUser>
</template>
<style scoped lang="scss">
.btn {
  padding: 0 25px;
}
.w-50 {
  flex: 0 0 50%;
}
</style>
