<script setup>
	import { message } from 'ant-design-vue'
	import RegionSelector from './RegionSelector/index.vue'
	import CommonSelector from '@/components/CommonSelector/index.vue'
	import {
		just_required,
		number_required,
		required_array,
		default_number_required,
		positive_integer_required
	} from '@/utils/rules'

	import { save, detail } from '@/api/emergencySupport/emergencyDeliveryCompany'
	import { clone, convertAllByField, deleteField, parseField2Float, parseField2Integer } from '@/utils/systemUtils'

	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 levelOptions = [
		{ label: '国家级', value: '1' },
		{ label: '省级', value: '2' },
		{ label: '市级', value: '3' },
		{ label: '县级', value: '4' }
	]

	const columns1 = [
		{
			title: '品种',
			dataIndex: 'title'
		},
		{
			title: '小麦原粮',
			dataIndex: 'val1'
		},
		{
			title: '稻谷原粮',
			dataIndex: 'val2'
		},
		{
			title: '大豆原粮',
			dataIndex: 'val3'
		},
		{
			title: '玉米原粮',
			dataIndex: 'val4'
		},
		{
			title: '其他原粮',
			dataIndex: 'val5'
		},
		{
			title: '小麦粉成品粮',
			dataIndex: 'val6'
		},
		{
			title: '大米成品粮',
			dataIndex: 'val7'
		},
		{
			title: '食用油成品粮',
			dataIndex: 'val8'
		},
		{
			title: '其他成品粮',
			dataIndex: 'val9'
		}
	]

	const columns2 = [
		{
			title: '品种',
			dataIndex: 'title'
		},
		{
			title: '小麦',
			dataIndex: 'val10'
		},
		{
			title: '稻谷日加工量',
			dataIndex: 'val11'
		},
		{
			title: '油料处理日产量',
			dataIndex: 'val12'
		},
		{
			title: '油料精炼日产量',
			dataIndex: 'val13'
		},
		{
			title: '油脂分装日产量',
			dataIndex: 'val14'
		},
		{
			title: '其它日加工量',
			dataIndex: 'val15'
		}
	]

	const dataSource1 = ref([])
	// const dataSource2 = ref([])

	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 parseDataResp = (resp) => {
		const d = resp
		d.level = []
		if (d.isNationalLevel) {
			d.level.push('1')
		}
		if (d.isProvincialLevel) {
			d.level.push('2')
		}
		if (d.isCityLevel) {
			d.level.push('3')
		}
		if (d.isCountyLevel) {
			d.level.push('4')
		}
		d.region1 = [d.managementAreaProvince, d.managementAreaCity, d.managementAreaCounty]
		d.region2 = [d.actualAddressProvince, d.actualAddressCity, d.actualAddressCounty]
		resetTable()
		const list = d.esDeliveryEnterpriseGrainList || []
		list.forEach((temp) => {
			const type = temp.type
			const gtype = temp.grainVariety
			const dsd = dataSource1.value.find((ds) => ds.type == type)
			dsd[`val${gtype}`] = temp.quantity
		})
		formData.value = d
	}

	const getData = () => {
		detail({ id: props.editData.id }).then(parseDataResp)
	}

	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 法人联系方式
			enterpriseContact: 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 归口管理地区-省；dev_dict的id；
			managementAreaCity: null, // string 归口管理地区-市；dev_dict的id；
			managementAreaCounty: null, // string 归口管理地区-县；dev_dict的id；
			isNationalLevel: null, // boolean 供应应急级别-是否国家级
			isProvincialLevel: null, // boolean 供应应急级别-是否省级
			isCityLevel: null, // boolean 供应应急级别-是否市级
			isCountyLevel: null, // boolean 供应应急级别-是否县级
			actualAddressProvince: null, // string 实际经营地址-省；dev_dict的id；
			actualAddressCity: null, // string 实际经营地址-市；dev_dict的id；
			actualAddressCounty: null, // string 实际经营地址-县；dev_dict的id；
			dailyDeliveryCapacity: null, // number 实际日配送量（吨/天）
			ownTransportVehicles: null, // integer(int32) 自有运输车辆数（辆）
			ownVehiclesDailyDeliveryCapacity: null, // number 自有车辆日配送能力（吨）
			ownTransportCapacity: null, // number 自有运输能力（吨）
			grainWarehouseCapacity: null, // number	原粮库房仓容
			vegetableOilTankCapacity: null, // number 原粮油罐罐容
			finishedGrainWarehouseCapacity: null, // number	成品粮库房容
			finishedOilTankCapacity: null, // number 成品粮油罐容,
			radiationRange: null // string 辐射范围(省/市/县）
		}

		resetTable()
	}

	const resetTable = () => {
		// 类型 1：日入库量；2：日销量；3：日库存；4：日加工量；5：日加工能力；
		// 粮食品种 1：小麦原粮:2：稻谷原粮:3：大豆原粮；4：玉米原粮；5：其他原粮；6：小麦粉成品粮；
		// 7：大米成品粮；8：食用油成品粮；9：其他成品粮；10：日加工-小麦；11：日加工-稻谷日加工量；
		// 12：日加工-油料处理日产量；13：日加工-油料精炼日产量；14：日加工-油脂分装日产量；15：日加工-其它日加工量；
		const list1 = []
		for (const type of [
			{ title: '日入库量(吨)', code: 1 },
			{ title: '日销量(吨)', code: 2 },
			{ title: '日库存(吨)', code: 3 }
		]) {
			const d = {
				type: type.code,
				title: type.title
			}
			for (const grainVariety of [1, 2, 3, 4, 5, 6, 7, 8, 9]) {
				d[`val${grainVariety}`] = null
			}
			list1.push(d)
		}
		dataSource1.value = list1
		// const list2 = []
		// for (const type of [
		// 	{ title: '日加工量(吨)', code: 4 },
		// 	{ title: '日加工能力(吨)', code: 5 }
		// ]) {
		// 	const d = {
		// 		type: type.code,
		// 		title: type.title
		// 	}
		// 	for (const grainVariety of [10, 11, 12, 13, 14, 15]) {
		// 		d[`val${grainVariety}`] = null
		// 	}
		// 	list2.push(d)
		// }
		// dataSource2.value = list2
	}

	const formRules = {
		enterpriseName: just_required,
		creditCode: just_required,
		legalRepresentative: just_required,
		legalContact: just_required,
		enterpriseNature: just_required,
		enterpriseType: just_required,
		longitude: number_required(6),
		latitude: number_required(6),
		actualBusinessAddress: just_required,
		region1: required_array,
		region2: required_array,
		level: required_array,
		productionStatus: just_required,
		dailyDeliveryCapacity: default_number_required,
		ownTransportVehicles: positive_integer_required,
		ownVehiclesDailyDeliveryCapacity: default_number_required,
		ownTransportCapacity: default_number_required,
		emergencyCategory: just_required,
		radiationRange: just_required
	}

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

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

	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 emit = defineEmits(['update:visible', 'on-approve', 'on-save'])

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

	const submitLoading = ref(false)
	const getLocalData = () => {
		const d = {
			...formData.value
		}
		const l = d.level
		d.isNationalLevel = l.find((d) => d === '1') ? true : false
		d.isProvincialLevel = l.find((d) => d === '2') ? true : false
		d.isCityLevel = l.find((d) => d === '3') ? true : false
		d.isCountyLevel = l.find((d) => d === '4') ? true : false
		d.esDeliveryEnterpriseGrainAddParamList = clone([...dataSource1.value]).flatMap((d) => {
			const ret = []
			Object.keys(d)
				.filter((k) => k.startsWith('val'))
				.forEach((k) => {
					if (d[k]) {
						const m = k.match(/\d{1,2}$/)
						const grainVariety = parseInt(m[0])
						ret.push({
							type: d.type,
							grainVariety,
							quantity: d[k]
						})
					}
				})
			return ret
		})

		convertAllByField(d.esDeliveryEnterpriseGrainAddParamList, 'quantity', parseFloat)
		deleteField(d, ['region1', 'region2', 'level'])
		parseField2Float(d, [
			'longitude',
			'latitude',
			'dailyDeliveryCapacity',
			'ownVehiclesDailyDeliveryCapacity',
			'ownTransportCapacity',
			'grainWarehouseCapacity',
			'vegetableOilTankCapacity',
			'finishedGrainWarehouseCapacity',
			'finishedOilTankCapacity'
		])
		parseField2Integer(d, ['dailyDeliveryCapacity'])

		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()
			})
		})
	}
</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="enterpriseContact">
						<a-input :disabled="readonly" v-model:value="formData.enterpriseContact" />
					</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="radiationRange">
						<a-input :disabled="readonly" v-model:value="formData.radiationRange" />
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="42">
				<a-col :span="16">
					<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="8">
					<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="24">
					<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-row :gutter="42">
				<a-col :span="8">
					<a-form-item label="原粮库房仓容" name="grainWarehouseCapacity">
						<a-input :disabled="readonly" v-model:value.trim="formData.grainWarehouseCapacity" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="原粮油罐罐容" name="vegetableOilTankCapacity">
						<a-input :disabled="readonly" v-model:value.trim="formData.vegetableOilTankCapacity" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="成品粮库房容" name="finishedGrainWarehouseCapacity">
						<a-input :disabled="readonly" v-model:value.trim="formData.finishedGrainWarehouseCapacity" />
					</a-form-item>
				</a-col>
			</a-row>
			<a-row :gutter="42">
				<a-col :span="8">
					<a-form-item label="成品粮油罐容" name="finishedOilTankCapacity">
						<a-input :disabled="readonly" v-model:value.trim="formData.finishedOilTankCapacity" />
					</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="dailyDeliveryCapacity">
						<a-input :disabled="readonly" v-model:value.trim="formData.dailyDeliveryCapacity" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="自有运输车辆数（辆）" name="ownTransportVehicles">
						<a-input :disabled="readonly" v-model:value.trim="formData.ownTransportVehicles" />
					</a-form-item>
				</a-col>
				<a-col :span="8">
					<a-form-item label="自有车辆日配送能力（吨）" name="ownVehiclesDailyDeliveryCapacity">
						<a-input :disabled="readonly" v-model:value.trim="formData.ownVehiclesDailyDeliveryCapacity" />
					</a-form-item>
				</a-col>
			</a-row>

			<a-row :gutter="42">
				<a-col :span="8">
					<a-form-item label="自有运输能力（吨）" name="ownTransportCapacity">
						<a-input :disabled="readonly" v-model:value.trim="formData.ownTransportCapacity" />
					</a-form-item>
				</a-col>
			</a-row>

			<a-table :columns="columns1" :data-source="dataSource1" 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" />
					<a-input v-if="column.dataIndex == 'val5'" v-model:value="record.val5" :disabled="readonly" />
					<a-input v-if="column.dataIndex == 'val6'" v-model:value="record.val6" :disabled="readonly" />
					<a-input v-if="column.dataIndex == 'val7'" v-model:value="record.val7" :disabled="readonly" />
					<a-input v-if="column.dataIndex == 'val8'" v-model:value="record.val8" :disabled="readonly" />
					<a-input v-if="column.dataIndex == 'val9'" v-model:value="record.val9" :disabled="readonly" />
					<!--					<span v-else>{{ text }}</span>-->
				</template>
			</a-table>

			<!--			<a-table :columns="columns2" :data-source="dataSource2" bordered :pagination="false" style="margin-top: 10px">-->
			<!--				<template #bodyCell="{ column, text, record }">-->
			<!--					<a-input v-if="column.dataIndex == 'val10'" v-model:value="record.val10" :disabled="readonly" />-->
			<!--					<a-input v-if="column.dataIndex == 'val11'" v-model:value="record.val11" :disabled="readonly" />-->
			<!--					<a-input v-if="column.dataIndex == 'val12'" v-model:value="record.val12" :disabled="readonly" />-->
			<!--					<a-input v-if="column.dataIndex == 'val13'" v-model:value="record.val13" :disabled="readonly" />-->
			<!--					<a-input v-if="column.dataIndex == 'val14'" v-model:value="record.val14" :disabled="readonly" />-->
			<!--					<a-input v-if="column.dataIndex == 'val15'" v-model:value="record.val15" :disabled="readonly" />-->
			<!--					&lt;!&ndash;					<span v-else>{{ text }}</span>&ndash;&gt;-->
			<!--				</template>-->
			<!--			</a-table>-->
		</a-form>
		<template #footer>
			<a-button style="margin-right: 8px" @click="close">取消</a-button>
			<a-button style="margin-right: 8px" v-if="!readonly" type="primary" @click="onSave" :loading="submitLoading">
				保存
			</a-button>
		</template>
	</xn-form-container>
</template>

<style scoped></style>
