import { CloseCircleOutlined, MinusCircleOutlined, PlusOutlined } from '@ant-design/icons';
import { Button, Card, Col, Form, Popover, Row, message, Divider, Select, Input, Upload } from 'antd';
import type { FormInstance } from 'antd';
import { history, useLocation } from 'umi';
import type { Location } from 'umi';

import type { FC } from 'react';
import React, { useState, Fragment, useRef } from 'react';
import ProForm, {
  ProFormSelect,
  ProFormText,
  ProFormRadio,
  ProFormDigit,
  ProFormDependency,
  ProFormUploadButton,
} from '@ant-design/pro-form';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import { submitForm } from './service';
import styles from './style.less';
import {
  fundNatureOptions,
  fundsProviderOptions,
  budgetTypeOptions,
  regionDictTypeOptions,
  regionOutsideOptions,
  currencyCodeOptions,
  purchaseTypeEnum,
  openTenderFormEnum,
  reviewMethodEnum,
  organizationFormEnum,
  tenderAgencyEnum,
  bidMethodEnum,
  evaluationMethodEnum,
  reviewWayEnum,
  processEnum,
  subjectTypeOptions,
  subjectType2Options,
} from './dict';
import CitySelect from '@/components/CitySelect';


type InternalNamePath = (string | number)[];

const fieldLabels = {
  projectName: '项目名称',
  ProjectBizNo: '项目编号',
  tendereeOrgId: '项目归属单位', //
  tendereeId: '项目归属部门', //
  appManagerId: '项目负责人',
  appManagerTel: '联系电话',
  fundNature: '资金性质', //
  fundsProviderDict: '资金来源',
  budgetType: '预算类型', //
  regionDictType: '项目所在行政区域类型', //?
  regionDict: '项目所在行政区域', //?
  budgetAmount: '项目预算',
  currencyCode: '币种',
  openTenderForm: '招标类型',
  bidMethodDict: '采购方式',
  reviewMethod: '资审方式', //
  bidOrgDict: '组织形式', //
  tenderAgencyId: '招标代理机构', //
};


interface ErrorField {
  name: InternalNamePath;
  errors: string[];
}

// 主要标的表单控件
const SubjectFormItem = ({ value = [], onChange, disabled = false }: { value?: string[], onChange?: (value: string[]) => void, disabled?: boolean }) => {
  return (
    <Row gutter={8}>
      <Col span={8}>
        <Select
          value={value[0]}
          onChange={(v1: string) => onChange?.([v1, value[1] || ''])}
          placeholder="请选择主要标的类别"
          disabled={disabled}
        >
          {subjectTypeOptions.map(item => (
            <Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>
          ))}
        </Select>
      </Col>
      <Col span={16}>
        <Select
          value={value[1]}
          onChange={(v2: string) => onChange?.([value[0] || '', v2])}
          placeholder="请选择主要标的类别"
          disabled={disabled}
        >
          {subjectType2Options.map(item => (
            <Select.Option key={item.value} value={item.value}>{item.label}</Select.Option>
          ))}
        </Select>
      </Col>
    </Row>
  )
}

const normFile = (e: any) => {
  console.log('Upload event:', e);
  if (Array.isArray(e)) {
    return e;
  }
  return e?.fileList;
};

const ProjectFileCreate: FC<Record<string, any>> = () => {
  const { query }: Location = useLocation();
  const readOnly = query?.action === 'view';
  const id = query?.id; // 文件 id

  const formRef = useRef<FormInstance>();
  const [error, setError] = useState<ErrorField[]>([]);
  const getErrorInfo = (errors: ErrorField[]) => {
    const errorCount = errors.filter((item) => item.errors.length > 0).length;
    if (!errors || errorCount === 0) {
      return null;
    }
    const scrollToField = (fieldKey: string) => {
      const labelNode = document.querySelector(`label[for="${fieldKey}"]`);
      if (labelNode) {
        labelNode.scrollIntoView(true);
      }
    };
    const errorList = errors.map((err) => {
      if (!err || err.errors.length === 0) {
        return null;
      }
      const key = err.name[0] as string;
      return (
        <li key={key} className={styles.errorListItem} onClick={() => scrollToField(key)}>
          <CloseCircleOutlined className={styles.errorIcon} />
          <div className={styles.errorMessage}>{err.errors[0]}</div>
          <div className={styles.errorField}>{fieldLabels[key as keyof typeof fieldLabels]}</div>
        </li>
      );
    });
    return (
      <span className={styles.errorIcon}>
        <Popover
          title="表单校验信息"
          content={errorList}
          overlayClassName={styles.errorPopover}
          trigger="click"
          getPopupContainer={(trigger: HTMLElement) => {
            if (trigger && trigger.parentNode) {
              return trigger.parentNode as HTMLElement;
            }
            return trigger;
          }}
        >
          <CloseCircleOutlined />
        </Popover>
        {errorCount}
      </span>
    );
  };

  const onFinish = async (values: Record<string, any>) => {
    setError([]);
    try {
      console.log(values);
      await submitForm(values);
      message.success('提交成功');
    } catch {
      // console.log
    }
  };

  const onFinishFailed = (errorInfo: any) => {
    setError(errorInfo.errorFields);
  };

  return (
    <div className={styles.createProjectFile} style={{ backgroundColor: '#f8f8f8' }}>
      <ProForm
        layout="horizontal"
        requiredMark
        formRef={formRef}
        submitter={{
          searchConfig: {
            submitText: '建档完成',
          },
          render: (props, dom) => {
            if (readOnly) {
              return (
                <FooterToolbar className={styles.footerToolbar}>
                  <Button key="cancel" onClick={() => {
                    history.replace('/ProjectFiles');
                  }}>
                    返回
                  </Button>
                </FooterToolbar>
              );
            }
            const _dom = dom.filter((item: JSX.Element) => item.key !== 'rest').concat([
              <Button key="stash" type="primary" onClick={() => {
                console.log('暂存');
              }}>
                暂存
              </Button>
            ]).concat([
              <Button key="cancel" onClick={() => {
                history.replace('/ProjectFiles');
              }}>
                取消
              </Button>
            ]);
            return (
              <FooterToolbar className={styles.footerToolbar}>
                {getErrorInfo(error)}
                {_dom}
              </FooterToolbar>
            );
          },
        }}
        initialValues={{
          budgetType: '1',
          regionDictType: '1',
          budgetAmount: 0,
          currencyCode: 'CNY',
          bidSection: [{
            bidSectionIndex: 1,
            bidSectionName: '',
            bidSectionNo: '',
            bidSectionBudget: 0,
            bidMethod: '',
            bidSectionCategory: [{
              type: [],
              percent: 0,
            }],
          }],
        }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 19 }}
      >
        <PageContainer title="新建项目" style={{ paddingBottom: 50 }}>
          <Card title="招标项目概况" className={styles.card} bordered={false}>
            <Row gutter={16}>
              <Col span={12}>
                <ProFormText
                  label={fieldLabels.projectName}
                  name="projectName"
                  rules={[{ required: true, message: '请输入项目名称' }]}
                  placeholder="请输入"
                  fieldProps={{
                    disabled: readOnly,
                  }}
                />
              </Col>
              <Col span={12}>
                <ProFormText
                  label={fieldLabels.ProjectBizNo}
                  name="ProjectBizNo"
                  rules={[{ required: true, message: '请输入项目编号' }]}
                  placeholder="请输入"
                  fieldProps={{
                    disabled: readOnly,
                  }}
                />
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <ProFormText
                  label={fieldLabels.tendereeOrgId}
                  name="tendereeOrgId"
                  rules={[{ required: true, message: '请输入项目归属单位' }]}
                  fieldProps={{
                    disabled: true,
                  }}
                  placeholder="请输入"
                />
              </Col>
              <Col span={12}>
                <ProFormText
                  label={fieldLabels.tendereeId}
                  name="tendereeId"
                  rules={[{ required: true, message: '请输入项目归属部门' }]}
                  fieldProps={{
                    disabled: true,
                  }}
                  placeholder="请输入"
                />
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <ProFormText
                  label={fieldLabels.appManagerId}
                  name="appManagerId"
                  rules={[{ required: true, message: '请输入项目负责人' }]}
                  placeholder="请输入"
                  fieldProps={{
                    disabled: readOnly,
                  }}
                />
              </Col>
              <Col span={12}>
                <ProFormText
                  label={fieldLabels.appManagerTel}
                  name="appManagerTel"
                  rules={[{ required: true, message: '请输入联系电话' }]}
                  fieldProps={{
                    disabled: readOnly,
                  }}
                />
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <ProFormSelect
                  label={fieldLabels.fundNature}
                  name="fundNature"
                  rules={[{ required: true, message: '请选择资金性质' }]}
                  options={fundNatureOptions}
                  fieldProps={{
                    disabled: readOnly,
                  }}
                />
              </Col>
              <Col span={12}>
                <ProFormSelect
                  label={fieldLabels.fundsProviderDict}
                  name="fundsProviderDict"
                  rules={[{ required: true, message: '请选择资金来源' }]}
                  options={fundsProviderOptions}
                  fieldProps={{
                    disabled: readOnly,
                  }}
                />
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <ProFormSelect
                  label={fieldLabels.budgetType}
                  name="budgetType"
                  rules={[{ required: true, message: '请选择预算类型' }]}
                  options={budgetTypeOptions}
                  fieldProps={{
                    disabled: readOnly,
                  }}
                />
              </Col>
              <Col span={12}>
                <ProFormRadio.Group
                  name="regionDictType"
                  label={fieldLabels.regionDictType}
                  rules={[{ required: true, message: '请选择项目所在行政区域类型' }]}
                  options={regionDictTypeOptions}
                  fieldProps={{
                    disabled: readOnly,
                    onChange: () => {
                      formRef.current?.setFieldsValue({
                        regionDict: undefined,
                      });
                    },
                  }}
                />
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <ProFormDependency name={['bidSection']}>
                  {({ bidSection }) => {
                    // 计算所有标段预算之和
                    const total = Array.isArray(bidSection)
                      ? bidSection.reduce((sum, item) => sum + (parseFloat(item?.bidSectionBudget) || 0), 0)
                      : 0;
                    return (
                      <ProFormDigit
                        label={fieldLabels.budgetAmount}
                        name="budgetAmount"
                        fieldProps={{
                          precision: 2,
                          value: total,
                          disabled: true,
                        }}
                      />
                    );
                  }}
                </ProFormDependency>
              </Col>
              <Col span={12}>
                <ProFormDependency name={['regionDictType']}>
                  {({ regionDictType }, ...rest) => {
                    console.log(rest);
                    return (
                      <>
                        {regionDictType === '1' ? (
                          <ProForm.Item
                            name="regionDict"
                            label={<span>&#8203;</span>}
                            required={false}
                            colon={false}
                            rules={[
                              {
                                required: true,
                                validator: (_, value) => {
                                  if (!value || !value.province || !value.city || !value.district) {
                                    return Promise.reject(new Error('请完整选择省市区'));
                                  }
                                  return Promise.resolve();
                                }
                              }
                            ]}
                          >
                            <CitySelect
                              placeholder={{
                                province: '请选择省份',
                                city: '请选择城市',
                                district: '请选择区域',
                              }}
                              disabled={readOnly}
                            />
                          </ProForm.Item>
                        ) : (
                          <ProFormSelect
                            name="regionDict"
                            label={<span>&#8203;</span>}
                            required={false}
                            colon={false}
                            rules={[{ required: true, message: '请选择项目所在行政区域' }]}
                            options={regionOutsideOptions}
                            placeholder="请选择行政区域"
                            fieldProps={{
                              disabled: readOnly,
                            }}
                          />
                        )}
                      </>
                    );
                  }}
                </ProFormDependency>
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <ProFormSelect
                  label={fieldLabels.currencyCode}
                  name="currencyCode"
                  rules={[{ required: true, message: '请选择币种' }]}
                  options={currencyCodeOptions}
                  fieldProps={{
                    disabled: readOnly,
                  }}
                />
              </Col>
              <Col span={12}>
                <ProFormSelect
                  label={fieldLabels.openTenderForm}
                  name="openTenderForm"
                  rules={[{ required: true, message: '请选择招标类型' }]}
                  valueEnum={openTenderFormEnum}
                  fieldProps={{
                    disabled: readOnly,
                  }}
                />
              </Col>
            </Row>
          </Card>
          <Card title="拟采用的招标方式和组织形式" className={styles.card} bordered={false}>
            <Row gutter={16}>
              <Col span={12}>
                <ProFormSelect
                  label={fieldLabels.bidMethodDict}
                  name="bidMethodDict"
                  rules={[{ required: true, message: '请选择采购方式' }]}
                  valueEnum={purchaseTypeEnum}
                  fieldProps={{
                    disabled: readOnly,
                  }}
                />
              </Col>
              <Col span={12}>
                <ProFormSelect
                  label={fieldLabels.reviewMethod}
                  name="reviewMethod"
                  rules={[{ required: true, message: '请选择资审方式' }]}
                  valueEnum={reviewMethodEnum}
                  fieldProps={{
                    disabled: readOnly,
                  }}
                />
              </Col>
            </Row>
            <Row gutter={16}>
              <Col span={12}>
                <ProFormSelect
                  label={fieldLabels.bidOrgDict}
                  name="bidOrgDict"
                  rules={[{ required: true, message: '请选择组织形式' }]}
                  valueEnum={organizationFormEnum}
                  fieldProps={{
                    disabled: readOnly,
                  }}
                />
              </Col>
              <Col span={12}>
                <ProFormSelect
                  label={fieldLabels.tenderAgencyId}
                  name="tenderAgencyId"
                  rules={[{ required: true, message: '请选择招标代理机构' }]}
                  valueEnum={tenderAgencyEnum}
                  fieldProps={{
                    disabled: readOnly,
                  }}
                />
              </Col>
            </Row>
          </Card>
          <Card title="标段（包）信息" className={styles.card} bordered={false}>
            <Row>
              <Col span={24}>
                <Form.List name="bidSection">
                  {(fields, { add, remove }) => (
                    <>
                      <Row style={{ marginBottom: 16 }}>
                        <Col span={24}>
                          <Button type="primary" onClick={() => add({ bidSectionIndex: fields.length + 1, bidSectionCategory: [{ type: [], percent: 0 }] })} disabled={readOnly}>
                            新增标段
                          </Button>
                        </Col>
                      </Row>
                      {fields.map(field => (
                        <Fragment key={field.key}>
                          {field.key !== 0 && <Divider />}
                          <Row >
                            <Col span={8}>
                              <ProFormText
                                {...field}
                                label="标段序号"
                                name={[field.name, 'bidSectionIndex']}
                                readonly
                              />
                            </Col>
                            <Col span={8}>
                              <ProFormText
                                {...field}
                                label="标段名称"
                                name={[field.name, 'bidSectionName']}
                                rules={[{ required: true, message: '请输入标段名称' }]}
                                fieldProps={{
                                  disabled: readOnly,
                                }}
                              />
                            </Col>

                            <Col span={8}>
                              <Button danger onClick={() => remove(field.name)} style={{ marginLeft: 16 }} hidden={fields.length === 1} disabled={readOnly}>
                                删除标段
                              </Button>
                            </Col>

                            <Col span={8}>
                              <ProFormText
                                {...field}
                                label="标段编号"
                                name={[field.name, 'bidSectionNo']}
                                rules={[{ required: true, message: '请输入标段编号' }]}
                                fieldProps={{
                                  disabled: readOnly,
                                }}
                              />
                            </Col>
                            <Col span={8} style={{ position: 'relative' }}>
                              <ProFormDependency name={['currencyCode']}>
                                {({ currencyCode }) => {
                                  return (
                                    <>
                                      <ProFormDigit
                                        label="标段预算"
                                        name={[field.name, 'bidSectionBudget']}
                                        rules={[{ required: true, message: '请输入标段预算' }]}
                                        fieldProps={{ precision: 2, style: { width: '80%' } }}
                                        disabled={readOnly}
                                      />
                                      <span style={{ position: 'absolute', right: '6%', top: 5 }}>{currencyCode}</span>
                                    </>
                                  );
                                }}
                              </ProFormDependency>
                            </Col>

                            <Col span={8} />

                            <Col span={8}>
                              <ProFormSelect
                                label="报价方式"
                                name={[field.name, 'bidMethod']}
                                rules={[{ required: true, message: '请选择报价方式' }]}
                                valueEnum={bidMethodEnum}
                                fieldProps={{
                                  disabled: readOnly,
                                }}
                              />
                            </Col>
                            <Col span={8}>
                              <ProFormSelect
                                label="评价方法"
                                name={[field.name, 'evaluationMethod']}
                                rules={[{ required: true, message: '请选择评价方法' }]}
                                valueEnum={evaluationMethodEnum}
                                fieldProps={{
                                  disabled: readOnly,
                                }}
                              />
                            </Col>
                            <Col span={8}>
                              <ProFormSelect
                                label="资格审查方法"
                                name={[field.name, 'reviewWay']}
                                rules={[{ required: true, message: '请选择资格审查方法' }]}
                                valueEnum={reviewWayEnum}
                                fieldProps={{
                                  disabled: readOnly,
                                }}
                              />
                            </Col>
                            <Col span={8}>
                              <ProFormSelect
                                label="流程类型"
                                name={[field.name, 'process']}
                                rules={[{ required: true, message: '请选择流程类型' }]}
                                valueEnum={processEnum}
                                fieldProps={{
                                  disabled: readOnly,
                                }}
                              />
                            </Col>
                            <Col span={8}>
                              <ProFormDigit
                                label="评标专家人数"
                                name={[field.name, 'reviewExpertCount']}
                                rules={[{ required: true, message: '请输入评标专家人数' }]}
                                fieldProps={{ precision: 0, disabled: readOnly }}
                                min={0}
                              />
                            </Col>
                            <Col span={8} />

                            <Col span={24}>
                              <Form.List name={[field.name, 'bidSectionCategory']} >
                                {(subFields, { add: addCategory, remove: removeCategory }) => (
                                  <>
                                    {subFields.map(subField => (
                                      <Fragment key={subField.key}>
                                        <Row gutter={8}>
                                          <Col span={8}>
                                            <Form.Item label="主要标的类别" name={[subField.name, 'type']} rules={[
                                              {
                                                required: true,
                                                validator: (_, value) => {
                                                  if (!value || !value[0] || !value[1]) {
                                                    return Promise.reject(new Error('请完整选择主要标的类别'));
                                                  }
                                                  return Promise.resolve();
                                                }
                                              }
                                            ]}>
                                              <SubjectFormItem disabled={readOnly} />
                                            </Form.Item>
                                          </Col>
                                          <Col span={8} style={{ paddingLeft: 2, position: 'relative' }}>
                                            <ProFormDigit
                                              label="主要标的类别占百分比"
                                              name={[subField.name, 'percent']}
                                              rules={[{ required: true, message: '请输入主要标的类别占百分比' }]}
                                              fieldProps={{ precision: 2, style: { width: '80%' } }}
                                              disabled={readOnly}
                                            />
                                            <span style={{ position: 'absolute', right: '8%', top: 5 }}>%</span>
                                          </Col>
                                          <Col span={1} hidden={subFields.length === 1}>
                                            <MinusCircleOutlined style={{ fontSize: 16, marginTop: 7, color: 'red' }} onClick={() => removeCategory(subField.name)} disabled={readOnly} />
                                          </Col>
                                        </Row>
                                      </Fragment>
                                    ))}
                                    <Row>
                                      <Col span={16}>
                                        <Button type="dashed" onClick={() => addCategory()} block icon={<PlusOutlined />} disabled={readOnly}>
                                          增加主要标的类别
                                        </Button>
                                      </Col>
                                    </Row>
                                  </>
                                )}
                              </Form.List>
                            </Col>
                          </Row>
                        </Fragment>
                      ))}
                    </>
                  )}
                </Form.List>
              </Col>
            </Row>

          </Card>
          <Card title="备注" className={styles.card} bordered={false}>
            <Form.Item name="remark" labelCol={{ span: 0 }} wrapperCol={{ span: 24 }}>
              <Input.TextArea
                autoSize={{ minRows: 3 }}
                placeholder="请输入备注"
                onPressEnter={(e) => {
                  e.preventDefault();
                }}
                disabled={readOnly}
              />
            </Form.Item>
          </Card>
          <Card title="附件信息" className={styles.card} bordered={false}>
            <Form.Item name="attachments" labelCol={{ span: 0 }} wrapperCol={{ span: 24 }} valuePropName="fileList" getValueFromEvent={normFile}>
              <ProFormUploadButton
                extra="支持格式：.rar .zip .doc .docx .pdf, 单个文件不超过20M"
                name="file"
                title="上传文件"
                accept='.rar,.zip,.doc,.docx,.pdf'
                disabled={readOnly}
                // action={'/api/file/upload'}
                fieldProps={{
                  beforeUpload: (file) => {
                    const isRarOrZipOrDocOrDocxOrPdf = file.type === 'application/x-rar-compressed' ||
                      file.type === 'application/zip' ||
                      file.type === 'application/msword' ||
                      file.type === 'application/vnd.openxmlformats-officedocument.wordprocessingml.document' ||
                      file.type === 'application/pdf';

                    if (!isRarOrZipOrDocOrDocxOrPdf) {
                      message.error('你只能上传 rar/zip/doc/docx/pdf 文件!');
                      return Upload.LIST_IGNORE;
                    }

                    const isLt20M = file.size / 1024 / 1024 < 20;
                    if (!isLt20M) {
                      message.error('文件大小不能超过 20MB!');
                      return Upload.LIST_IGNORE;
                    }

                    return true;
                  },
                }}
              />
            </Form.Item>
          </Card>
        </PageContainer>
      </ProForm>
    </div>
  );
};

export default ProjectFileCreate;