/*
 * @Author: zzy 411037547@qq.com
 * @Date: 2022-07-29 16:37:44
 * @LastEditors: zzy 411037547@qq.com
 * @LastEditTime: 2022-08-01 09:53:47
 * @FilePath: \cloud-platform\src\pages\account\center\components\MyServerpart\index.tsx
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import ProList from "@ant-design/pro-list";
import useRequest from '@ahooksjs/use-request';

import { connect } from "umi";
import { useRef, useState } from "react";
import { PlusOutlined } from "@ant-design/icons";
import { Space, Tag, Typography, Empty, Button, message } from "antd";
import { ModalForm, ProFormSelect, ProFormTextArea } from "@ant-design/pro-form";

import type { CurrentUser } from "umi";
import type { FormInstance } from "antd";
import type { ConnectState } from "@/models/connect";
import type { ServerpartTree } from "@/services/options";
import { PermissionApplyDetailModel, PermissionApplyModel, PermissionProinstModel } from "@/pages/account/center/data";

import { createPermissionProInst } from "@/pages/account/center/sevice";
import { getServerpartOption } from '@/services/options';

import './index.less'

// 提交权限变更审批单
const savePermissionProinst = async (fields: PermissionProinstModel) => {
	const hide = message.loading('正在提交...');

	const result = await createPermissionProInst(fields);
	hide();
	if (result.Result_Code !== 100) {
		message.error(`${result.Result_Desc}` || `${result.Result_Code}:提交失败`);
		return false;
	}
	message.success('提交审批成功！');
	return true;
};

type ServerpartProps =
	{
		serverpartList: ServerpartTree[],
		currentUser?: CurrentUser
	}

/**
 * @description: 我的门店组件
 * @param {ServerpartProps} ServerpartProps 组件接收的参数
 * @return {*} 函数组件
 */
const ServerpartCardList: React.FC<ServerpartProps> = ({ serverpartList, currentUser }: ServerpartProps) => {
	const formRef = useRef<FormInstance>()
	const [modalVisible, handleModalVisible] = useState<boolean>(false)

	const [permissionApplyDetail] = useState<PermissionApplyDetailModel[]>([])
	const [permissionApply, setPermissionApply] = useState<PermissionApplyModel>({
		STAFF_ID: currentUser?.ID, // 操作人内码
		STAFF_NAME: currentUser?.Name || '', // 操作人员
		USER_MOBILEPHONE: currentUser?.UserMobilephone || '', // 手机号
		PERMISSIONAPPLY_STATE: 2000,
		SOURCE_PLATFORM: 1
	})
	const { data: serverpartOpt } = useRequest(() => { return getServerpartOption(currentUser?.ProvinceCode, currentUser?.CityAuthority || '1') }) // 已授权的服务区
	const { data: serverpartTotalOpt } = useRequest(() => { return getServerpartOption(currentUser?.ProvinceCode, '0') })	// 所有服务区

	// 生成服务区门店列表卡片
	const severpartCard = (severpartList: ServerpartTree[], title: string, index: number) => (
		<ProList<ServerpartTree>
			key={index}
			grid={{ gutter: 16, column: 5 }}
			className="severpart-prolist-card"
			rowKey="value"
			headerTitle={<Typography.Text strong>{title}</Typography.Text>}
			dataSource={severpartList}
			metas={{
				title: {
					dataIndex: 'label',
				},
			}}
			toolBarRender={() => {
				return index === 0 ? [
					<Button
						key="new"
						icon={<PlusOutlined />}
						type="primary"
						onClick={() => {
							setPermissionApply({ ...permissionApply, PERMISSIONAPPLY_TYPE: 5000 })
							handleModalVisible(true)
						}}>
						权限变更
					</Button>,
				] : [];
			}}
		/>

	)

	return (
		<div>
			{
				serverpartList ? serverpartList.map((n: ServerpartTree, index) => n.type === 0 ?
					severpartCard(n.children ? n.children : [], n.label, index) : '') : <Empty />
			}
			{
				serverpartList.find(n => n.type === 1) ? severpartCard(serverpartList.filter(n => n.type === 1), '其他区域', serverpartList.find(n => n.type === 0) ? -1 : 0) :
					severpartCard([], '', serverpartList.find(n => n.type === 0) ? -1 : 0)
			}
			{<ModalForm
				title={'服务区权限变更'}
				layout={"horizontal"}
				wrapperCol={{ span: 16 }}
				labelCol={{ span: 6 }}
				labelAlign="right"
				formRef={formRef}
				visible={modalVisible}
				width={600}
				autoFocusFirstInput
				modalProps={{
					onCancel: () => {
					},
				}}
				onVisibleChange={(value) => {
					handleModalVisible(value);
					formRef.current?.resetFields();
				}}
				onFinish={async (values) => {
					let ServerpartIds = ''
					if (values.ServerpartNewIds && values.ServerpartNewIds.toString().split(',').length > 0) {
						ServerpartIds = values.ServerpartNewIds.toString();
						values.ServerpartNewIds.toString().split(',').forEach(element => {
							permissionApplyDetail.push({
								PERMISSIONAPPLYDETAIL_TYPE: 2000,
								SERVERPART_ID: element.value
							} as PermissionApplyDetailModel)
						});
					}
					if (values.ServerpartRemoveIds && values.ServerpartRemoveIds.toString().split(',').length > 0) {
						ServerpartIds = (ServerpartIds ? `${ServerpartIds},` : '') + values.ServerpartRemoveIds.toString();
						values.ServerpartRemoveIds.toString().split(',').forEach(element => {
							permissionApplyDetail.push({
								PERMISSIONAPPLYDETAIL_TYPE: 1000,
								SERVERPART_ID: element.value
							} as PermissionApplyDetailModel)
						});
					}
					const newValue = {
						...permissionApply,
						SERVERPART_IDS: ServerpartIds,
						// SERVERPART_NAME: currentRow?.SERVERPART_NAME,
						PERMISSIONAPPLY_REASON: values.PERMISSIONAPPLY_REASON,
						PERMISSIONAPPLY_DATE: new Date()
					}

					const success = await savePermissionProinst({
						PermissionApplyModel: newValue,
						PermissionApplyDetailList: permissionApplyDetail
					})
					if (success) {
						return true
					}
					return false
				}}
			>
				<ProFormSelect
					name="ServerpartNewIds"
					label="新增服务区"
					mode="multiple"
					placeholder="请选择需要新增的服务区"
					dependencies={['value']}
					// rules={[
					// 	{
					// 		required: true,
					// 		message: '请选择需要新增的服务区',
					// 	},
					// ]}
					showSearch
					request={() => { return serverpartTotalOpt }}
				/>
				<ProFormSelect
					name="ServerpartRemoveIds"
					label="移除服务区"
					mode="multiple"
					placeholder="请选择需要移除的服务区"
					dependencies={['value']}
					// rules={[
					// 	{
					// 		required: true,
					// 		message: '请选择需要移除的服务区',
					// 	},
					// ]}
					showSearch
					request={() => { return serverpartOpt }}
				/>
				<ProFormTextArea
					name="PERMISSIONAPPLY_REASON"
					label="申请说明"
					rules={[
						{
							required: true,
							message: '请输入申请说明',
						},
					]}
				/>
			</ModalForm>}
		</div >
	);
}

export default connect(({ user }: ConnectState) => ({
	currentUser: user.currentUser
}))(ServerpartCardList);