import * as service from '../AffairPage/publicApiService';
import moment from 'moment';
import { isJSON } from '@/baseComponent/utils';
import { getDefaultValues } from '../AffairPage/destruction';
import { message } from 'antd';

const text = [
	'BINARY',
	'BIT',
	'BLOB',
	'CHAR',
	'GEOMETRY',
	'GEOMETRYCOLLECTION',
	'JSON',
	'LINESTRING',
	'LONGBLOB',
	'LONGTEXT',
	'MEDIUMBLOB',
	'MEDIUMINT',
	'MEDIUMTEXT',
	'MULTILINESTRING',
	'MULTIPOINT',
	'MULTIPOLYGON',
	'POINT',
	'POLYGON',
	'REAL',
	'DECIMAL',
	'ENUM',
	'SET',
	'TEXT',
	'TINYBLOB',
	'TIBYTEXT',
	'VARBINARY',
	'VARCHAR',
];

const optionsStatus = [
	{
		label: '未提交',
		value: 'un_audit',
	},
	{
		label: '审核中',
		value: 'in_audit',
	},
	{
		label: '已通过',
		value: 'audited',
	},
  {
    label: '已驳回',
    value: 'reject',
  },
	// { label: '已拒绝', value: 'refuse' },
	{
		label: '已失效',
		value: 'invalid',
	},
	// { label: '已挂起', value: 'hang_up' },
	{
		label: '已终止',
		value: 'termination',
	},
	// { label: '已驳回', value: 'reject' },
	// { label: '已同意', value: 'agree' },
	{
		label: '重新提交',
		value: 're_apply',
	},
	{
		label: '己拒绝',
		value: 'bad_audited',
	},
];

const number = ['BIGINT', 'DOUBLE', 'FLOAT', 'INT', 'INTEGER', 'NUMERIC', 'SMALLINT', 'TINYINT'];

const date = ['DATE', 'DATETIME', 'TIME', 'TIMESTAMP', 'YEAR'];

const format = {
	// 欢哥那边定义好的 时间格式类型
	DATE: 'YYYY-MM-DD HH:mm',
	DATETIME: 'YYYY-MM-DD HH:mm:ss',
	TIME: 'HH:mm:ss',
	TIMESTAMP: 'HH:mm:ss',
	YEAR: 'YYYY',
};
const taskNode = ['TASKNODE'];

/**
 * 将时间格式转化为unix时间戳
 * */
const transLateTimeTOUnix = (value, dataType) => {
	if (date.indexOf(dataType) > -1 && value) {
		return moment(value).format('x');
	} else {
		return value;
	}
};

const getFormArrayConfig = (header) => {
	let config = [];
	for (let item of header) {
		if (item.isPrimaryKey || item.isHidden || item.dataIndex === 'operationEdit') {
			// 主键
			continue;
			/* config.push(
         {
           key: item.name,
           name: item.title,
           type: 'input',
           placeholder: `请输入${item.name}`,
           required: !item.isNull,
         }
       );*/
		} else if (item.options && Array.isArray(item.options) && item.options.length) {
			config.push({
				key: item.name,
				name: item.title,
				type: 'select',
				required: !item.isNull,
				base52: item.base52,
				options: item.options,
			});
		} else if (text.indexOf(item.type) > -1) {
			config.push({
				key: item.name,
				name: item.title,
				type: 'input',
				placeholder: `请输入${item.title}`,
				required: !item.isNull,
				base52: item.base52,
			});
		} else if (number.indexOf(item.type) > -1) {
			config.push({
				key: item.name,
				name: item.title,
				type: 'inputNumber',
				placeholder: `请输入${item.title}`,
				required: !item.isNull,
				min: 0,
				base52: item.base52,
			});
		} else if (date.indexOf(item.type) > -1) {
			config.push({
				key: item.name,
				name: item.title,
				type: 'datePicker',
				placeholder: `请输入${item.title}`,
				required: !item.isNull,
				format: format[item.type],
				base52: item.base52,
			});
		} else {
			config.push({
				key: item.name,
				name: item.title,
				type: 'input',
				placeholder: `请输入${item.title}`,
				required: !item.isNull,
				base52: item.base52,
			});
		}
	}
	return config;
};

const transLate = {
	TextArea: 'textarea',
	Radio: 'radioGroup',
	Label: 'text',
	Checkbox: 'checkBoxMutiple',
	Select: 'select',
	Switch: 'switch',
	DatePicker: 'datePicker',
	RangePicker: 'rangePicker',
	UploadCom: 'buttonUpload',
	ImgUploadCom: 'upload',
	VideoUploadCom: 'upload',
	Input: 'input',
	TableSelect: 'tableSelect', // 表格选择
	ChildForm: 'childForm', // 最终保存的数据还有问题
	InputNumber: 'inputNumber',
	PartForm: 'partForm', // 还未开发 相当于选了一个选项 表单字段变更
	Echart: 'echart', //  不做
	Description: 'input', // 'description', // 还未开发
	Table: 'table', // 表格 未开发
};

const getOpts = async (item) => {
	let options = [];
	if (item.optionType === 'reference') {
		options = await service.getOptions(
			item.dataId,
			item.filterSql,
			item.referenceCodeName,
			item.referenceNameName,
		);
	} else if (item.optionType === 'sql') {
		options = await service.getSqlOptions(item.dataId, item.sqlKey, item.valueName, item.labelName);
	} else {
		options = item.options;
	}
	return options;
};

const getSearchCondition = async (id, appId = undefined) => {
	const searchHeaders = await service.getHead(id).then((res) => {
		if (res && res.length) {
			return res.filter((x) => {
				return x.isShowQuery !== false && x.isHidden === false;
			});
		} else {
			return [];
		}
	});
	// console.log(JSON.stringify(searchHeaders));
	for (let item of searchHeaders) {
		// H:\project\one_stop_front\src\pages\AdminSystem\pages\ddl\formList\index.js
		if (item.referenceObjId && item.id && item.referenceCodeName && item.referenceNameName) {
			//通过引用去查枚举
			item.options = await service.getBatchOptions(item.id).then((res) => {
				if (res && res[item.id]) {
					return res[item.id]
						.filter((g) => {
							return !!g[item.referenceNameName] && !!g[item.referenceCodeName];
						})
						.map((y) => {
							return {
								key: y[item.referenceCodeName],
								name: y[item.referenceNameName],
							};
						});
				} else {
					return [];
				}
			});
		}

		if (item.isGroupQuery && item.id && (!item.options || !item.options.length)) {
			// 获取下拉搜索条件的枚举项

			if (item.name === 'process_status') {
				/**
				 * 29890 活动发布管理/活动申报审核/通知活动审核，“活动名称”没有显示；筛选输入有误（103123，bdk@2022*$）
				 * 2022年9月26日
				 * 可能需要修改 流程审核状态的枚举
				 *
				 * 2023-04-17 和雅职2.0的枚举 保持一致!!
				 * 解决禅道 34123
				 * */
				// item.name = 'formStatusId';
				item.options = optionsStatus.map((x) => {
					return {
						key: x.value,
						name: x.label,
					};
				});
				// item.options = [
				//   {
				//     key: '0',
				//     name: '已通过',
				//   },
				//   {
				//     key: '1',
				//     name: '已拒绝',
				//   },
				//   {
				//     key: '2',
				//     name: '已驳回',
				//   },
				//   {
				//     key: '-1',
				//     name: '审核中',
				//   },
				// ];
			} else {
				item.options = await service
					.getGroupList({
						columnId: item.id,
						appId,
					})
					.then((res) => {
						if (res && Array.isArray(res)) {
							return res
								.filter((x) => {
									return x.value !== item.title && x.value;
								})
								.map((x) => {
									return {
										key: x.value,
										name: x.value,
									};
								});
						} else {
							return [];
						}
					});
			}
		}
	}

	const condition = getFormArrayConfig(searchHeaders);

	condition.forEach((x) => {
		x.required = false;
	});
	return condition;
};

const translateAddFields = async (data, tableInfo) => {
	let key = [];
	let res = [];
	for (let item of data) {
		if (key.indexOf(item.key) > -1) {
			continue;
		} else {
			key.push(item.key);
		}
		item.type = transLate[item.comName] || 'input';
		if (typeof item.key === 'undefined' || !item.key) {
			item.key = item.c1;
		}
		switch (item.comName) {
			case 'Input':
				if (number.indexOf(item.dataType) > -1) {
					item.type = 'inputNumber';
				}
				break;
			case 'DatePicker':
				item.format = item.format || format[item.dataType];
				// console.log(item.format);
				if (item.format && item.format.indexOf('HH') > -1) {
					item.showTime = true;
				}
				break;
			case 'RangePicker':
				item.name = item.name || '起止时间';
				item.endKey = item.c2;
				item.format = item.format || format[item.dataType];
				if (item.format.indexOf('HH') > -1) {
					item.showTime = true;
				}
				break;
			case 'ChildForm':
				item.componentProps.thisFields = await translateAddFields(
					item.componentProps.thisFields,
					tableInfo,
				);
				break;
			case 'Radio':
				item.options = await getOpts(item);
				break;
			case 'Select':
				item.options = await getOpts(item);
				break;
			case 'Checkbox':
				item.options = await getOpts(item);
				item.options = item.options.map((x) => {
					return {
						label: x.name,
						value: x.key,
					};
				});
				break;
			case 'TableSelect':
				let info = await service.handleSqlfind(item.componentProps.sqlKey);
				if (isJSON(info.cols)) {
					info.cols = JSON.parse(info.cols);
				}
				item.componentProps.columnsData = info;
				item.componentProps.allValues = JSON.stringify(getDefaultValues(data, tableInfo));
				break;
			default:
				break;
		}
		res.push(item);
	}
	return res;
};

const mustHaveValue = (configFields, data) => {
	for (let item of configFields) {
		if (item.required && !data[item.key] && data[item.key] !== false && data[item.key] !== 0) {
			message.warning(`${item.name}是必填项请填写`);
			return false;
		}
		if (item.required && typeof data[item.key] === 'object') {
			if (data[item.key].selects && JSON.stringify(data[item.key].selects) === '{}') {
				message.warning(`${item.name}是必填项请填写`);
				return false;
			}
		}
	}
	return true;
};

export {
	text,
	number,
	date,
	getFormArrayConfig,
	translateAddFields,
	transLateTimeTOUnix,
	format,
	mustHaveValue,
	taskNode,
	getSearchCondition,
};
