import { AddReq, CreateCrudOptionsProps, dict,CreateCrudOptionsRet, UserPageQuery,compute } from '@fast-crud/fast-crud';
import * as api from './api';
import { auth } from '/@/utils/authFunction';
import dayjs from 'dayjs';
import { Ref } from 'vue';
import axios from 'axios';
import { successMessage,warningMessage } from '/@/utils/message';
import { Session } from '/@/utils/storage';

export const createCrudOptions = function ({ crudExpose , inventoryDialog, inventoryDetailDialog}: CreateCrudOptionsProps& { inventoryDialog: Ref<any>, inventoryDetailDialog: Ref<any> }): CreateCrudOptionsRet {
	const pageRequest = async (query: UserPageQuery) => {
		return await api.GetList(query);
	};
	const editRequest = async ({ form, row }: EditReq) => {
		form.id = row.id;
		return await api.UpdateObj(form);
	};
	const delRequest = async ({ row }: DelReq) => {
		return await api.DelObj(row.id);
	};
	const addRequest = async ({ form }: AddReq) => {
		return await api.AddObj(form);
	};

	return {
		crudOptions: {
			request: {
				pageRequest,
				addRequest,
				editRequest,
				delRequest,

			},
			form:{
				wrapper: {
					buttons: {
						ok:{
							text:'提交',
														show:compute((row) => {
															return row.mode !=='view'
														})
						}
					}
				}
			},
			actionbar: {
				buttons: {
					add: {
						show: false,
					},
					startTaking: {
						text: '开始盘点',
						// icon: 'el-icon-document',
						click: async () => {
					const res =await api.StartScan({ remark: '例行盘点' });
					if (res?.code === 2000) {
						await inventoryDialog.value.setCheckNo(res.data.check_no, res.data.id); 
						inventoryDialog.value.visible = true; 
					}
					},
					},

				},
			},
			toolbar:{
				show:false,
			},
			rowHandle:{
				fixed: 'right',
				width: 220,
				buttons:{
					view:{
						show:true,
						click: async ({ row }) => {
							try {
								const res = await api.GetDetail(row.id);
								if (res?.code === 2000) {
									inventoryDetailDialog.value.openWithData(res.data);
									return;
								}
								warningMessage(res?.message || '获取详情失败');
							} catch (e) {
								console.error(e);
								warningMessage('获取详情异常');
							}
						}
					},
					remove:{
						show:false,
					},
					edit:{
						show:false,
					},
					reanalyze: { // 添加重新分析按钮
						text: '取消',
						iconRight: '',
						type:'danger',
						show:compute(({ row }) => {
							return row.status === 0; // 只在状态为"已面试"时显示
						}),
						order: 2,
						click: async ({ row }) => {
							try {
								// 先调用视频分析接口
								const videoAnalysisResponse = await axios.post(`${import.meta.env.VITE_API_URL}/api/system/inventory/check-records/${row.id}/cancel/`,{},{
									headers: {
										'authorization':`JWT ${Session.get('token')}`
									}
								});
								console.log(videoAnalysisResponse);
								
								 if (videoAnalysisResponse.data.code == 2000) {
									successMessage(videoAnalysisResponse.data.msg || "盘点已取消");
									crudExpose.doSearch()
									return;
								}
								
								/*// 视频分析成功后，调用综合分析接口
								const response = await axios.post(`${import.meta.env.VITE_API_URL}/api/system/job/trigger_comprehensive_analysis`, {
									application_id: row.id,
									force_trigger: true
								});
								
								if (response.data.code === 2000) {
									successMessage('取消成功');
									// 刷新当前页面数据
									crudExpose.doRefresh();
								} else {
									warningMessage(response.data.message || '取消成失败');
								} */
							} catch (error) {
								console.error('取消失败:', error);
								warningMessage('取消失败');
							}
						}
					},

				}

			},
			pagination: {
				show: true,
			},		
			columns: {
				_index: {
					title: '序号',
					form: { show: false },
					column: {
						type: 'index',
						align: 'center',
						width: '70px',
						columnSetDisabled: true, //禁止在列设置中选择
					},
				},
				check_no: {
					title: '编号',
					search: {
						show: true,
					},
					treeNode: true,
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						show:true,
						rules: [
							// 表单校验规则
							{ required: true, message: '名称必填项' },
						],
						component: {
							placeholder: '请输入',
						},
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},
				start_time:{
					title: '盘点日期',
					type: 'datetime',
					column: {
						minWidth: 120,
						// formatter: ({ value }) => (value ? dayjs(value).format('YYYY-MM-DD') : ''),
					},
					form: {
						show:false,
						component: { placeholder: '请填写盘点日期' },
						rules: [{ required: true, message: '请填写盘点日期' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					},
					valueResolve({ form, value }) {
						form.start_time = value ? dayjs(value).format('YYYY-MM-DD HH:mm:ss') : null;
					},
					// valueBuilder({ form, value }) {
					// 	console.log("valuessss::",value)
					// 	form.start_time =  value ;
					// },
				},
				checker_name:{
					title: '盘点人',
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						show:false,
						component: { placeholder: '请填写盘点人' },
						rules: [{ required: false, message: '请填写盘点人' }],
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: false, message: '' }],
					}
				},
				status_display: {
					title: '状态',
					search: {
						show: false,
					},
					treeNode: true,
					type: 'input',
					column: {
						minWidth: 120,
					},
					form: {
						show:false,
						rules: [
							// 表单校验规则
							{ required: true, message: '维护标题必填项' },
						],
						component: {
							placeholder: '请输入维护标题',
						},
					},
					viewForm:{
						component: { placeholder: '' },
						rules: [{ required: true, message: '' }],
					}
				},	
				

			
			},
		},
	};
};
