import { RESPONSE_CODE } from '@/constants/enum';
import {
  postCanrdApiUserAddressList,
  postCanrdApiUserList,
  postResearchGroupsAdd,
  postResearchGroupsDetail,
  postResearchGroupsEdit,
} from '@/services';
import { getDefaultString, isEmpty } from '@/utils/StringUtil';
import { getRandomNumber } from '@/utils/numberUtil';
import { getSalesCodeOptions } from '@/utils/order';
import { validatePhoneNumberBool } from '@/utils/validators';
import {
  ModalForm,
  ProCard,
  ProForm,
  ProFormSelect,
  ProFormText,
} from '@ant-design/pro-components';
import { Button, Form, Spin, message } from 'antd';
import { cloneDeep } from 'lodash';
import { useEffect, useState } from 'react';
import '../index.less';

// import { cloneDeep } from 'lodash';
export default ({ setVisible, researchGroupId, onClose }) => {
  const [form] = Form.useForm();
  const [salesCodeOptions, setSalesCodeOptions] = useState([]);
  const [memberOptions, setMemberOptions] = useState<any[]>([]);
  const [accountOptions, setAccountOptions] = useState<any[]>([]);
  const [researchGroupInfo, setResearchGroupInfo] = useState<any>(null);
  const [modalLoading, setModalLoading] = useState(false);
  const groupId = cloneDeep(researchGroupId);
  const [requestCount, setRequestCount] = useState(1);

  /**
   * 获取课题组信息
   * @returns
   */
  const loadResearchGroupInfo = async () => {
    if (groupId === null) {
      return;
    }
    setModalLoading(true);
    let res = await postResearchGroupsDetail({ data: { id: groupId } });
    if (res && res.result === RESPONSE_CODE.SUCCESS) {
      setResearchGroupInfo(res.data);
    }
    setModalLoading(false);
  };

  /**
   * 获取销售代码枚举,在复制和编辑的时候判断是否为旧的代码
   */
  const loadSalesCodeOptions = async () => {
    let options = await getSalesCodeOptions();
    setSalesCodeOptions(options);
  };

  /**
   * 对options去重
   * @param options
   * @returns
   */
  function deduplicateOptions(options: any) {
    const seen = new Set();
    const result: any[] = [];
    options.forEach((option: any) => {
      const uniqueKey = `${option.realName}-${option.phone}`;
      if (!seen.has(uniqueKey)) {
        seen.add(uniqueKey);
        result.push(option);
      }
    });
    return result;
  }

  /**
   * 自动填充客户信息
   * @param option
   */
  function autoFillCustomerInfo(option: any) {
    if (!option) {
      return;
    }
    let realName = option.realName;
    let id = option.value;
    if (id === 3.1415926) {
      message.warning(
        '请填写下方的【客户名称】和【手机号】,填写完成确保信息无误后点击添加按钮。',
      );
      form.setFieldValue('realName', option.name);
      return;
    }
    //判断当前客户信息是否已添加过:id匹配或者option的phone匹配说明添加过了
    let memberIds = form.getFieldValue('members');
    if (!memberIds) {
      //表单项没值的时候默认是undefined。初始化为数组
      memberIds = [];
    }
    if (memberIds.includes(id)) {
      message.info(`${realName} 重复添加`);
      return;
    }
    //表单项的value添加当前option的value
    memberIds.push(id);
    form.setFieldValue('members', memberIds);
    message.success(`${realName} 添加成功`);
    //判断options中是否已经有这个option
    for (let memberOption of memberOptions) {
      if (
        memberIds.includes(memberOption.value) &&
        memberOption.phone === option.phone
      ) {
        return;
      }
    }
    //option添加到memberOptions中
    let newMemberOptions = [...memberOptions];
    newMemberOptions.push(option);
    setMemberOptions(newMemberOptions);

    //清空信息
    form.setFieldValue('realName', undefined);
    form.setFieldValue('phone', undefined);
    form.setFieldValue('customerName', null);
  }

  /**
   * 保存account的options
   * @param option
   * @returns
   */
  function autoAccountSelectOptions(option: any) {
    if (!option) {
      return;
    }
    let id = option.value;
    //判断当前客户信息是否已添加过:id匹配或者option的phone匹配说明添加过了
    let accountIds = form.getFieldValue('accounts');
    if (!accountIds) {
      //表单项没值的时候默认是undefined。初始化为数组
      accountIds = [];
    }
    if (accountIds.includes(id)) {
      return;
    }
    //option添加到accountOptions中
    setAccountOptions(option);
  }

  /**
   * 添加自定义成员
   */
  function addCustomMember() {
    let realName = form.getFieldValue('realName');
    let phone = form.getFieldValue('phone');
    if (isEmpty(realName)) {
      message.error('请填写客户名称');
    }
    if (isEmpty(phone)) {
      message.error('请填写手机号');
    }
    if (!validatePhoneNumberBool(phone)) {
      message.error('请填写正确格式的手机号');
      return;
    }
    let customOption = {
      value: getRandomNumber(10),
      realName: realName,
      phone: phone,
    };
    autoFillCustomerInfo(customOption);
  }

  function parseFormValues(values: any) {
    if (!values) {
      return {};
    }

    let memberIds = values.members;
    let accountIds = values.accounts;
    values.id = groupId;

    //成员对象封装
    if (memberIds) {
      let memberObjs: any[] = [];
      for (let memberOption of memberOptions) {
        if (memberIds.includes(memberOption.value)) {
          memberObjs.push({
            memberName: memberOption.realName,
            memberPhone: memberOption.phone,
            id: memberOption.id,
            groupId: memberOption.groupId,
          });
        }
      }
      values.members = memberObjs;
    }

    //预存账号对象封装
    if (accountIds) {
      let accountObjs: any[] = [];
      for (let accountOption of accountOptions) {
        if (accountIds.includes(accountOption.uid)) {
          accountObjs.push({
            accountPhone: accountOption.phone,
            accountId: accountOption.uid,
            accountName: accountOption.realName,
            id: accountOption.id,
            groupId: accountOption.groupId,
          });
        }
      }
      values.accounts = accountObjs;
    }

    return values;
  }

  /**
   * 设置表单默认信息
   * @returns
   */
  const loadFormDefaultValue = async () => {
    if (!researchGroupInfo) {
      return;
    }

    let members = researchGroupInfo.members;
    if (members !== null) {
      let newMemberOptions = [];
      for (let member of members) {
        let name = member.memberName;
        let phone = member.memberPhone;
        let id = member.id;
        newMemberOptions.push({
          ...member,
          realName: name,
          phone: phone,
          value: id,
        });
      }
      setMemberOptions(newMemberOptions);
      form.setFieldValue(
        'members',
        members?.map((item: any) => {
          return item.id;
        }),
      );
    }

    let accounts = researchGroupInfo.accounts;
    if (accounts !== null) {
      let phones: any[] = [];
      let accountIds = accounts
        .filter((account: any) => {
          //id为空的按照手机号查询
          if (account.accountId === null) {
            phones.push(account.accountPhone);
            return false;
          }
          return true;
        })
        .map((item: any) => item.accountId);

      let uidIdMap = new Map(
        accounts.map((item: any) => [item.accountId, item.id]),
      );
      let data = {};
      if (accountIds.length > 0) {
        data = { ...data, uids: accountIds };
      }
      if (phones.length > 0) {
        data = { ...data, phones: phones };
      }

      let res = await postCanrdApiUserList({ data });
      if (res && res.result === RESPONSE_CODE.SUCCESS) {
        let accountList = res?.data?.data;
        console.log(accountList);
        let newAccountOptions = accountList?.map((item) => {
          item.value = uidIdMap.get(item.uid);
          return item;
        });

        console.log(newAccountOptions);
        setAccountOptions(newAccountOptions);
      }

      form.setFieldValue('accounts', accountIds);
    }

    form.setFieldValue('groupName', researchGroupInfo.groupName);
    form.setFieldValue('leaderName', researchGroupInfo.leaderName);
    form.setFieldValue('companyName', researchGroupInfo.companyName);
  };

  useEffect(() => {
    loadSalesCodeOptions();
    loadResearchGroupInfo();
  }, []);

  useEffect(() => {
    loadFormDefaultValue();
  }, [researchGroupInfo]);

  return (
    <div className="research-group-index">
      <ModalForm
        width={800}
        open
        title="新增/编辑课题组"
        form={form}
        autoFocusFirstInput
        submitter={{}}
        modalProps={{
          okText: '提交',
          cancelText: '关闭',
          destroyOnClose: true,
          onCancel: () => {
            setVisible(false);
          },
        }}
        onFinish={async (values) => {
          let newValues = parseFormValues(values);
          let res;
          if (researchGroupInfo === null) {
            res = await postResearchGroupsAdd({
              data: newValues,
            });
          } else {
            res = await postResearchGroupsEdit({
              data: newValues,
            });
          }
          if (res && res.result === RESPONSE_CODE.SUCCESS) {
            message.success(res.message);
            onClose();
          }
        }}
        onOpenChange={setVisible}
      >
        <Spin spinning={modalLoading} tip="加载中...">
          <ProForm.Group>
            <ProFormText
              name="groupName"
              label="课题组名称"
              placeholder="请输入课题组名称"
              rules={[{ required: true, message: '请输入课题组名称' }]}
            />
            <ProFormText
              name="companyName"
              label="单位名称"
              placeholder="请输入单位名称"
              rules={[{ required: true, message: '请输入单位名称' }]}
            />
            <ProFormSelect
              name="leaderName"
              key="leaderName"
              width="lg"
              showSearch
              label="负责人"
              placeholder="请输入课题组负责人"
              //rules={[{ required: true, message: '请输入课题组负责人' }]}
              options={salesCodeOptions}
            />
          </ProForm.Group>

          <ProFormSelect
            name="accounts"
            key="accounts"
            width="lg"
            showSearch
            label="绑定预存账号(可多选)"
            placeholder="请选择预存账号"
            onChange={(_, option) => {
              autoAccountSelectOptions(option);
            }}
            //rules={[{ required: true, message: '请至少选择绑定一个预存账号' }]}
            fieldProps={{
              mode: 'multiple',
              filterOption() {
                return true;
              },
              optionItemRender(item: any) {
                let name =
                  item.label +
                  ' | ' +
                  item.institution +
                  ' | ' +
                  item.nowMoney +
                  '¥' +
                  ' | ' +
                  item.phone;
                return (
                  <div title={name}>
                    <span style={{ color: '#333333' }}>{name}</span>
                  </div>
                );
              },
            }}
            debounceTime={1000}
            request={async (value, {}) => {
              const keywords = value.keyWords;
              let body = {
                keywords: keywords,
                pageSize: 20,
                researchGroupId: undefined,
              };

              if (requestCount === 1) {
                body.researchGroupId = groupId;
              }

              const res = await postCanrdApiUserList({
                data: body,
              });
              let options = res?.data?.data?.map((c: any) => {
                return {
                  ...c,
                  label: c.realName,
                  value: c.uid,
                  key: c.uid,
                };
              });

              setRequestCount(requestCount + 1);
              return options;
            }}
          />

          {groupId && (
            <ProFormSelect
              name="members"
              key="members"
              width="lg"
              showSearch
              label="课题组成员"
              placeholder="请添加课题组成员"
              fieldProps={{
                mode: 'multiple',
                filterOption() {
                  return true;
                },
                optionItemRender(item: any) {
                  let name = item.realName + ' | ' + item.phone;
                  return (
                    <div title={name}>
                      <span style={{ color: '#333333' }}>{name}</span>
                    </div>
                  );
                },
              }}
              options={memberOptions}
            />
          )}

          {groupId && (
            <ProCard
              title="选择或自定义课题组成员信息"
              bordered
              tooltip="从【客户信息】选择框中可以直接搜索客户,选中后自动添加到【课题组成员】中。也可以自定义输入【客户名称】和【手机号】,点击添加按钮手动添加到【课题组成员】中。"
            >
              <ProForm.Group>
                <ProFormSelect
                  key="customerName"
                  label="客户信息(选择)"
                  width="lg"
                  showSearch
                  name="customerName"
                  placeholder="请选择客户信息"
                  onChange={(_, option) => {
                    autoFillCustomerInfo(option);
                  }}
                  fieldProps={{
                    filterOption() {
                      return true;
                    },
                    optionItemRender(item: any) {
                      if (item.type === 'add') {
                        return (
                          <div title={item.name + '(新增客户)'}>
                            <span style={{ color: '#333333' }}>
                              {item.name}
                            </span>
                            {' | '}
                            <span style={{ color: 'orange' }}>自定义</span>
                          </div>
                        );
                      }

                      let title = '';
                      let spanText = '';
                      let realName = item.realName;
                      let phone = item.phone;

                      title =
                        getDefaultString(realName) +
                        '|' +
                        getDefaultString(phone);

                      spanText =
                        getDefaultString(realName) +
                        '|' +
                        getDefaultString(phone);
                      return (
                        <div title={title}>
                          <span style={{ color: '#333333' }}>{spanText}</span>
                        </div>
                      );
                    },
                  }}
                  debounceTime={1000}
                  request={async (value, {}) => {
                    const keywords = value.keyWords;
                    if (keywords === '') {
                      return [];
                    }
                    const res = await postCanrdApiUserAddressList({
                      data: { keywords: keywords },
                    });
                    let options = res?.data?.map((c: any) => {
                      return {
                        ...c,
                        label: c.name,
                        value: c.id,
                        key: c.id,
                      };
                    });

                    //对options去重,realName和phone唯一
                    options = deduplicateOptions(options);

                    //第一个商品默认为要新增客户
                    if (keywords.trim() !== '') {
                      options.unshift({
                        name: keywords,
                        type: 'add',
                        label: keywords,
                        value: 3.1415926,
                        key: keywords,
                      });
                    }

                    return options;
                  }}
                />
              </ProForm.Group>

              <ProForm.Group>
                <ProFormText
                  name="realName"
                  label="客户名称(自定义)"
                  placeholder="请输入客户名称"
                  rules={[{ required: false, message: '请输入客户名称' }]}
                />
                <ProFormText
                  name="phone"
                  label="手机号(自定义)"
                  width="md"
                  placeholder="请输入手机号"
                  rules={[{ required: false, message: '请输入手机号' }]}
                />
              </ProForm.Group>
              <Button
                type="primary"
                onClick={() => {
                  addCustomMember();
                }}
              >
                添加
              </Button>
            </ProCard>
          )}
        </Spin>
      </ModalForm>
    </div>
  );
};