<template>
	<a-page-header style="padding: 10px; font-size: 20px" @back="handleBack">
		<template #extra>
			<a-button v-if="route.query.type !== 'SEARCH'" key="1" type="primary" @click="onSubmitForm">保存</a-button>
		</template>
	</a-page-header>

	<a-card :bordered="false" title="客户">
		<DynamicForm
			:allDisabled="route.query.type === 'SEARCH'"
			:formItems="clientFormItems"
			:model="formData"
			:rules="formRules"
			ref="formRef1"
		/>
	</a-card>

	<a-card :bordered="false" class="mt-4">
		<a-tabs v-model:activeKey="activeKey">
			<a-tab-pane key="1" tab="联系信息">
				<DynamicForm
					:allDisabled="route.query.type === 'SEARCH'"
					:formItems="baseFormItems"
					:model="formData"
					:rules="formRules"
					ref="formRef2"
				/>
			</a-tab-pane>
			<a-tab-pane key="2" tab="销售区域管理" force-render>
				<a-space>
					<a-button v-if="route.query.type !== 'SEARCH'" key="1" type="primary" @click="addRow">新增</a-button>
					<xn-batch-delete
						v-if="hasPerm('customerBatchDelete')"
						:selectedRowKeys="selectedListRowKeys"
						@batchDelete="deleteBatchRecords"
					/>
				</a-space>
				<a-table ref="tableRef" :dataSource="dataSource" :columns="columns" :row-selection="rowSelection" row-key="id">
					<template #bodyCell="{ column, record }">
						<template v-if="column.dataIndex === 'province'">
							<a-select
								style="width: 100%"
								:options="cityOptions"
								v-model:value="record.province"
								@change="
									(value, options) => {
										provinceChange(value, options, record)
									}
								"
							></a-select>
						</template>
						<template v-if="column.dataIndex === 'city'">
							<a-select
								style="width: 100%"
								:options="record.cityOptions"
								v-model:value="record.city"
								@change="
									(value, options) => {
										cityChange(value, options, record)
									}
								"
							></a-select>
						</template>
						<template v-if="column.dataIndex === 'county'">
							<a-select style="width: 100%" :options="record.countyOptions" v-model:value="record.county"></a-select>
						</template>
						<template v-if="column.dataIndex === 'remarks'">
							<a-textarea style="width: 100%" v-model:value="record.remarks"></a-textarea>
						</template>
					</template>
				</a-table>
			</a-tab-pane>
			<a-tab-pane key="3" tab="操作信息" v-if="route.query.type !== 'ADD'">
				<OperationalInformation :detailData="detailData" :colSpan="6"></OperationalInformation>
			</a-tab-pane>
		</a-tabs>
	</a-card>
</template>

<script setup name="clientDetail">
	import { required } from '@/utils/formRules'
	import sysBrandApi from '@/api/base/brand/sysBrandApi'
	import customerCategoryApi from '@/api/base/customer/customerCategoryApi'
	import customerApi from '@/api/base/customer/customerApi'

	import useFormHandler from '@/hook/useFormHandler'
	import tool from '@/utils/tool'
	import { useRoute } from 'vue-router'
	import cityOptions from '@/utils/cityOptions'
	const route = useRoute()

	const formRules = {
		name: [required('请输入名称')],
		type: [required('请输入类型')],
		appid: [required('请输入AppID')],
		secret: [required('请输入AppSecret')]
	}
	let detailData = reactive({})

	// 级联选择
	const onCascaderChange = (value) => {
		formData.province = value[0] && value[0]
		formData.city = value[1] && value[1]
		formData.county = value[2] && value[2]
	}

	const clientFormItems = reactive([
		{
			label: '编码：',
			name: 'number',
			type: 'a-input',
			span: 8,
			attrs: {
				placeholder: '请选择类型',
				options: tool.dictList('OFFICIAL_ACCOUNT_TYPE')
			}
		},
		{
			label: '名称：',
			name: 'name',
			type: 'a-input',
			span: 8,
			rules: [required('请输入名称')],
			attrs: {
				placeholder: '请输入名称',
				allowClear: true
			}
		},
		{
			label: '简称：',
			name: 'shortName',
			type: 'a-input',
			span: 8,
			attrs: {
				placeholder: '请输入名称',
				allowClear: true
			}
		},
		{
			label: '可用状态：',
			name: 'enabledState',
			type: 'a-select',
			span: 8,
			attrs: {
				placeholder: '请选择可用状态',
				options: tool.dictList('COMMON_STATUS')
			},
			defaultValue: 'ENABLE'
		},
		{
			label: '品牌：',
			name: 'brandId',
			type: 'a-select',
			span: 8,
			rules: [required('请选择品牌')],
			attrs: {
				placeholder: '请选择品牌',
				options: tool.dictList('COMMON_STATUS'),
				fieldNames: {
					label: 'name',
					value: 'id'
				}
			}
		},
		{
			label: '客户分类：',
			name: 'categoryId',
			type: 'a-tree-select',
			span: 8,
			rules: [required('请选择客户分类')],
			attrs: {
				placeholder: '请选择客户分类',
				allowClear: true,
				fieldNames: {
					children: 'children',
					label: 'name',
					value: 'id'
				}
			}
		},
		{
			label: '详细地址：',
			name: 'provinceName',
			type: 'a-cascader',
			span: 8,
			rules: [required('请选择详细地址')],
			attrs: {
				placeholder: '请选择详细地址',
				options: cityOptions,
				onChange: onCascaderChange
			}
		},
		{
			name: 'address',
			type: 'a-textarea',
			span: 24,
			attrs: {
				placeholder: '请输入详细地址',
				allowClear: true,
				fieldNames: {
					children: 'children',
					label: 'name',
					value: 'id'
				}
			}
		},
		{
			label: '备注：',
			name: 'remarks',
			type: 'a-textarea',
			span: 24,
			attrs: {
				placeholder: '请输入备注',
				allowClear: true
			}
		}
	])

	const baseFormItems = [
		{
			label: '联系人：',
			name: 'contacts',
			type: 'a-input',
			span: 6,
			attrs: {
				placeholder: '请选择类型'
			}
		},
		{
			label: '手机：',
			name: 'phone',
			type: 'a-input',
			span: 6,
			attrs: {
				placeholder: '请选择类型'
			}
		},
		{
			label: '固话：',
			name: 'tel',
			type: 'a-input',
			span: 6,
			attrs: {
				placeholder: '请选择类型'
			}
		},
		{
			label: '传真：',
			name: 'fax',
			type: 'a-input',
			span: 6,
			attrs: {
				placeholder: '请选择类型'
			}
		},
		{
			label: '电子邮箱：',
			name: 'email',
			type: 'a-input',
			span: 6,
			attrs: {
				placeholder: '请输入备注',
				allowClear: true
			}
		},
		{
			label: 'QQ：',
			name: 'qq',
			type: 'a-input',
			span: 6,
			attrs: {
				placeholder: '请输入备注',
				allowClear: true
			}
		},
		{
			label: '微信：',
			name: 'wechat',
			type: 'a-input',
			span: 6,
			attrs: {
				placeholder: '请输入备注',
				allowClear: true
			}
		},
		{
			label: '联系地址：',
			name: 'contactAddress',
			type: 'a-input',
			span: 6,
			attrs: {
				placeholder: '请输入备注',
				allowClear: true
			}
		}
	]

	const formRef1 = ref(null)
	const formRef2 = ref(null)

	const { formData, formRefs, onSubmit, handleBack, fetchData } = useFormHandler(
		[...clientFormItems, ...baseFormItems],
		{
			submitForm: customerApi.customerSubmitForm,
			getDetail: customerApi.customerDetail
		}
	)

	const onSubmitForm = () => {
		const dataSourceList = dataSource.value.map((item) => {
			return {
				id: item.id || '',
				customerId: item.customerId || '',
				province: item.province || '',
				city: item.city || '',
				county: item.county || '',
				remarks: item.remarks || ''
			}
		})
		onSubmit({
			isDeep: true,
			...formData,
			saleAreaList: dataSourceList
		})
	}

	onMounted(async () => {
		console.log(1)
		formRefs.value = [formRef1.value, formRef2.value]
		fetchData(route.query.type).then((res) => {
			if (res) {
				detailData = res

				formData.provinceName = [res.province, res.city, res.county]

				customerApi
					.customerSaleAreaList({
						customerId: res.id
					})
					.then((list) => {
						dataSource.value = list || []
					})
			}
		})

		// 选择品牌
		sysBrandApi
			.sysBrandList({
				enabledState: 'ENABLE'
			})
			.then((res) => {
				clientFormItems.forEach((item) => {
					if (item.name === 'brandId') {
						item.attrs.options = res
					}
				})
			})

		// 客户分类
		customerCategoryApi
			.customerCategoryTree({
				enabledState: 'ENABLE'
			})
			.then((res) => {
				clientFormItems.forEach((item) => {
					if (item.name === 'categoryId') {
						item.attrs.treeData = res
					}
				})
			})
	})

	let activeKey = ref('1')

	const dataSource = ref([])
	let selectedListRowKeys = ref([])
	let tableRef = ref(null)

	const provinceChange = (event, options, record) => {
		record.cityOptions = options.children
	}

	const cityChange = (event, options, record) => {
		record.countyOptions = options.children
	}

	const addRow = () => {
		const newRow = {
			id: Date.now().toString(),
			...columns.reduce((acc, col) => {
				if (col.dataIndex) acc[col.dataIndex] = ''
				return acc
			}, {})
		}
		dataSource.value = [...dataSource.value, newRow]
	}

	const deleteBatchRecords = (value) => {
		dataSource.value = dataSource.value.filter((item) => {
			return !value.some((itemValue) => itemValue.id === item.id)
		})
	}

	const rowSelection = {
		onChange: (selectedRowKeys, selectedRows) => {
			selectedListRowKeys.value = selectedRowKeys
		}
	}

	const columns = [
		{
			title: '省',
			dataIndex: 'province',
			editable: true,
			dataType: 'select', // 或 'number', 'select'
			attrs: {
				options: cityOptions,
				onChange: provinceChange,
				fliedNames: {
					label: 'label',
					value: 'code'
				}
			}
		},
		{
			title: '市',
			dataIndex: 'city',
			editable: true
		},
		{
			title: '区/县',
			dataIndex: 'county',
			editable: true
		},
		{
			title: '备注',
			dataIndex: 'remarks',
			editable: true
		}
	]
</script>
