<script setup>
	import RegionSelector from './RegionSelector/index.vue'
	import CommonSelector from '@/components/CommonSelector/index.vue'
	import { save, detail, approve, approveDetail } from '@/api/emergencySupport'
	import { just_required, number_required, required_array } from '@/utils/rules'
	import { clone, deleteField, parseField2Float, convertAllByField } from '@/utils/systemUtils'
	import { message } from 'ant-design-vue'

	const props = defineProps({
		visible: {
			type: Boolean,
			required: false,
			default: false
		},
		editData: {
			type: Object,
			required: false,
			default: null
		},
		action: {
			type: String,
			required: false,
			default: null
		}
	})

	const isView = computed(() => props.action === 'view')
	const isAdd = computed(() => props.action === 'add')
	const isEdit = computed(() => props.action === 'edit')
	const isApprove = computed(() => props.action === 'approve')
	const readonly = computed(() => {
		return isView.value || isApprove.value
	})

	const show = ref(props.visible)
	const formData = ref({})

	const init = () => {
		formData.value = {}
		if (isAdd.value) {
			resetForm()
		} else if (isApprove.value) {
			auditAdvice.value = null
			getApproveData()
		} else {
			getData()
		}
	}

	const parseDataResp = (resp) => {
		const d = resp
		d.level = []
		if (d.isNational) {
			d.level.push('1')
		}
		if (d.isProvincial) {
			d.level.push('2')
		}
		if (d.isCity) {
			d.level.push('3')
		}
		if (d.isCounty) {
			d.level.push('4')
		}
		d.region1 = [d.managementAreaProvince, d.managementAreaCity, d.managementAreaCounty]
		d.region2 = [d.actualAddressProvince, d.actualAddressCity, d.actualAddressCounty]
		resetTable()
		d.esNetworkEntryGrainList.forEach((temp) => {
			const type = temp.type
			const gtype = temp.grainVariety
			const dsd = dataSource.value.find((ds) => ds.type == type)
			dsd[`val${gtype}`] = temp.quantity
		})
		formData.value = d

		if (isView.value || isEdit.value || isApprove.value) {
			nextTick(() => {
				loadOptions()
			})
		}
	}

	const getApproveData = () => {
		approveDetail({ id: props.editData.id }).then(parseDataResp)
	}
	const regionRef1 = ref()
	const regionRef2 = ref()
	const loadOptions = () => {
		regionRef1.value.loadOptions()
		regionRef2.value.loadOptions()
	}
	const getData = () => {
		console.log(123123)
		detail({ id: props.editData.id }).then(parseDataResp)
		//getDetails({ id: props.editData.id }).then((resp) => {
		//	console.log(resp)
		//	formData.value = resp
		//})
	}

	watch(
		() => props.visible,
		(n, o) => {
			if (n) {
				init()
			}
			show.value = n
		}
	)

	const resetForm = () => {
		formData.value = {
			region1: [],
			region2: [],
			level: [],

			enterpriseName: null, // string 企业名称
			creditCode: null, // string 统一社会信用代码
			establishmentTime: null, // string(date-time) 成立时间
			headquarterCreditCode: null, // string 所属总公司企业信用代码
			legalRepresentative: null, // string 法人姓名
			legalContact: null, // string 法人联系方式
			contactPerson: null, // string 联系人姓名
			contactNumber: null, // string 联系电话
			cityState: null, // string 所属市州
			enterpriseNature: null, // string 企业性质
			enterpriseType: null, // string 企业类型
			longitude: null, // number 经度
			latitude: null, // number 纬度
			emergencyCategory: null, // string 应急分类
			actualBusinessAddress: null, // string 实际经营地址（省、市、县、乡镇街道门牌号）
			productionStatus: null, // integer(int32) 生产状态，0：停产；1：生产
			managementAreaProvince: null, // string 归口管理地区-省
			managementAreaCity: null, // string 归口管理地区-市
			managementAreaCounty: null, // string 归口管理地区-县
			isNational: null, // boolean 供应应急级别-是否国家级
			isProvincial: null, // boolean 供应应急级别-是否省级
			isCity: null, // boolean 供应应急级别-是否市级
			isCounty: null, // boolean 供应应急级别-是否县级
			actualAddressProvince: null, // string 实际经营地址-省
			actualAddressCity: null, // string 实际经营地址-市
			actualAddressCounty: null, // string 实际经营地址-县
			status: null // integer(int32) 状态
		}
		resetTable()
	}

	const resetTable = () => {
		dataSource.value = [
			{
				type: 1,
				title: '日库存（吨）',
				val1: null,
				val2: null,
				val3: null,
				val4: null
			},
			{
				type: 2,
				title: '日销量（吨）',
				val1: null,
				val2: null,
				val3: null,
				val4: null
			},
			{
				type: 3,
				title: '日供应能力（吨）',
				val1: null,
				val2: null,
				val3: null,
				val4: null
			},
			{
				type: 4,
				title: '安全库存（吨）',
				val1: null,
				val2: null,
				val3: null,
				val4: null
			}
		]
	}

	const formRules = {
		enterpriseName: just_required,
		creditCode: just_required,
		legalRepresentative: just_required,
		legalContact: just_required,
		cityState: just_required,
		enterpriseNature: just_required,
		enterpriseType: just_required,
		longitude: number_required(6),
		latitude: number_required(6),
		actualBusinessAddress: just_required,
		productionStatus: just_required,
		region1: required_array,
		region2: required_array,
		level: required_array
	}

	const emit = defineEmits(['update:visible', 'on-approve', 'on-save'])

	const close = () => emit('update:visible', false)

	const submitLoading = ref(false)

	// 状态 0：待发起；1：已发起；2：驳回；3：已完成；
	const getLocalData = (status = 0) => {
		const d = {
			...formData.value,
			status
		}
		const l = d.level
		d.isNational = l.find((d) => d === '1') ? true : false
		d.isProvincial = l.find((d) => d === '2') ? true : false
		d.isCity = l.find((d) => d === '3') ? true : false
		d.isCounty = l.find((d) => d === '4') ? true : false
		d.categoryAddParamList = clone(dataSource.value).flatMap((d) => {
			const type = d.type
			const ret = []
			for (const t of [1, 2, 3, 4]) {
				const k = `val${t}`
				if (d[k]) {
					ret.push({
						type,
						grainVariety: t,
						quantity: d[k]
					})
				}
			}
			// return [
			// 	{
			// 		type,
			// 		grainVariety: 1,
			// 		quantity: d.val1
			// 	},
			// 	{
			// 		type,
			// 		grainVariety: 2,
			// 		quantity: d.val2
			// 	},
			// 	{
			// 		type,
			// 		grainVariety: 3,
			// 		quantity: d.val3
			// 	},
			// 	{
			// 		type,
			// 		grainVariety: 4,
			// 		quantity: d.val4
			// 	}
			// ]
			return ret
		})
		convertAllByField(d.categoryAddParamList, 'quantity', parseFloat)
		deleteField(d, ['region1', 'region2', 'level'])
		parseField2Float(d, ['longitude', 'latitude'])

		return d
	}
	const formRef = ref()
	const onSave = () => {
		formRef.value.validate().then((_) => {
			const d = getLocalData()
			console.log('save', d)
			save(d).then((resp) => {
				emit('on-save')
				close()
			})
		})
		// save(getLocalData())
		// close()
	}
	const auditAdvice = ref(null)
	// 1：已审核；2：驳回；
	const doApprove = (status) => {
		if (!auditAdvice.value) {
			return message.error('请填写审核意见')
		}
		approve({
			id: props.editData.id,
			auditAdvice: auditAdvice.value,
			auditStatus: status,
			type: formData.value.type,
			step: formData.value.step,
			requestId: formData.value.requestId
		}).then((resp) => {
			emit('on-approve')
			close()
		})
	}

	const onReject = () => {
		doApprove(2)
	}

	const onAgree = () => {
		doApprove(1)
	}

	const region1Changed = (v, n) => {
		if (v) {
			const [p, c1, c2] = v
			formData.value.managementAreaProvince = p || null
			formData.value.managementAreaCity = c1 || null
			formData.value.managementAreaCounty = c2 || null
		} else {
			formData.value.managementAreaProvince = null
			formData.value.managementAreaCity = null
			formData.value.managementAreaCounty = null
		}
	}
	const region2Changed = (v, n) => {
		if (v) {
			const [p, c1, c2] = v
			formData.value.actualAddressProvince = p || null
			formData.value.actualAddressCity = c1 || null
			formData.value.actualAddressCounty = c2 || null
		} else {
			formData.value.actualAddressProvince = null
			formData.value.actualAddressCity = null
			formData.value.actualAddressCounty = null
		}
	}

	const levelOptions = [
		{ label: '国家级', value: '1' },
		{ label: '省级', value: '2' },
		{ label: '市级', value: '3' },
		{ label: '县级', value: '4' }
	]

	const columns = [
		{
			title: '品种',
			dataIndex: 'title'
		},
		{
			title: '小麦粉成品粮',
			dataIndex: 'val1'
		},
		{
			title: '大米成品粮',
			dataIndex: 'val2'
		},
		{
			title: '食用油成品粮',
			dataIndex: 'val3'
		},
		{
			title: '其他成品粮',
			dataIndex: 'val4'
		}
	]

	const dataSource = ref([])
</script>

<template>
	<xn-form-container title="详细信息" width="80%" v-model:visible="show" :destroy-on-close="true" @close="close">
		<a-form ref="formRef" :model="formData" :rules="formRules" layout="vertical">
			<a-divider>详细信息</a-divider>
			<a-row :gutter="42">
				<a-col :span="8">
					<a-form-item label="企业名称" name="enterpriseName">
						<a-input :disabled="readonly" v-model:value="formData.enterpriseName" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="统一社会信用代码" name="creditCode">
						<a-input :disabled="readonly" v-model:value="formData.creditCode" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="成立时间" name="establishmentTime">
						<a-date-picker
							v-model:value="formData.establishmentTime"
							format="YYYY-MM-DD HH:mm:ss"
							:show-time="true"
							:disabled="readonly"
						/>
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="42">
				<a-col :span="8">
					<a-form-item label="所属总公司企业信用代码" name="headquarterCreditCode">
						<a-input :disabled="readonly" v-model:value="formData.headquarterCreditCode" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="法人姓名" name="legalRepresentative">
						<a-input :disabled="readonly" v-model:value="formData.legalRepresentative" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="法人联系方式" name="legalContact">
						<a-input :disabled="readonly" v-model:value="formData.legalContact" />
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="42">
				<a-col :span="8">
					<a-form-item label="联系人姓名" name="contactPerson">
						<a-input :disabled="readonly" v-model:value="formData.contactPerson" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="联系电话" name="contactNumber">
						<a-input :disabled="readonly" v-model:value="formData.contactNumber" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="所属市州" name="cityState">
						<a-input :disabled="readonly" v-model:value="formData.cityState" />
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="42">
				<a-col :span="8">
					<a-form-item label="企业性质" name="enterpriseNature">
						<a-input :disabled="readonly" v-model:value="formData.enterpriseNature" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="企业类型" name="enterpriseType">
						<a-input :disabled="readonly" v-model:value="formData.enterpriseType" />
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="42">
				<a-col :span="8">
					<a-form-item label="经度" name="longitude">
						<a-input :disabled="readonly" v-model:value.trim="formData.longitude" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="纬度" name="latitude">
						<a-input :disabled="readonly" v-model:value.trim="formData.latitude" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="应急分类" name="emergencyCategory">
						<a-input :disabled="readonly" v-model:value="formData.emergencyCategory" />
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="42">
				<a-col :span="16">
					<a-form-item label="实际经营地址（省、市、县、乡镇街道门牌号）" name="actualBusinessAddress">
						<a-input :disabled="readonly" v-model:value="formData.actualBusinessAddress" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="生产状态" name="productionStatus">
						<common-selector type="OPT1" v-model:value="formData.productionStatus" :readonly="readonly" />
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="42">
				<a-col :span="8">
					<a-form-item label="归口管理地区" name="region1">
						<region-selector
							ref="regionRef1"
							v-model:value="formData.region1"
							:readonly="readonly"
							@on-change="region1Changed"
						/>
					</a-form-item>
				</a-col>
				<a-col :span="16">
					<a-form-item label="供应应急级别" name="level">
						<a-checkbox-group
							v-model:value="formData.level"
							name="checkboxgroup"
							:options="levelOptions"
							:disabled="readonly"
						/>
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="42">
				<a-col :span="8">
					<a-form-item label="实际经营地" name="region2">
						<region-selector
							ref="regionRef2"
							v-model:value="formData.region2"
							:readonly="readonly"
							@on-change="region2Changed"
						/>
					</a-form-item>
				</a-col>
			</a-row>

			<a-table :columns="columns" :data-source="dataSource" bordered :pagination="false">
				<template #bodyCell="{ column, text, record }">
					<a-input v-if="column.dataIndex == 'val1'" v-model:value="record.val1" :disabled="readonly" />
					<a-input v-if="column.dataIndex == 'val2'" v-model:value="record.val2" :disabled="readonly" />
					<a-input v-if="column.dataIndex == 'val3'" v-model:value="record.val3" :disabled="readonly" />
					<a-input v-if="column.dataIndex == 'val4'" v-model:value="record.val4" :disabled="readonly" />
					<!--					<span v-else>{{ text }}</span>-->
				</template>
			</a-table>

			<a-row v-if="isApprove" :gutter="42">
				<a-col :span="24">
					<a-form-item label="审核意见" name="auditAdvice">
						<a-input v-model:value="auditAdvice" />
					</a-form-item>
				</a-col>
			</a-row>
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="close">关闭</a-button>
			<a-button
				v-if="isEdit || isAdd"
				style="margin-right: 8px"
				type="primary"
				@click="onSave"
				:loading="submitLoading"
			>
				保存
			</a-button>
			<a-button v-if="isApprove" style="margin-right: 8px" type="primary" @click="onReject" :loading="submitLoading">
				驳回
			</a-button>
			<a-button v-if="isApprove" style="margin-right: 8px" type="primary" @click="onAgree" :loading="submitLoading">
				通过
			</a-button>
		</template>
	</xn-form-container>
</template>

<style scoped></style>
