import React, { useEffect, useState } from 'react';
// import type { UploadProps } from 'antd';
// import { Cascader } from 'antd';
import { Cascader, Checkbox, Col, Form, Input, InputNumber, message, Modal, Row } from 'antd';
import { createUser, editUser, queryTreeList } from '@/services/setting';
// import { LoadingOutlined, PlusOutlined } from '@ant-design/icons';
import md5 from 'js-md5';
import { queryRoleList } from '@/services/role';
import { infoQuery } from '@/services/ReportingManagement';

interface userEditPros {
  visible: boolean;
  editCallback: () => void;
  detailData: any;
}

/**
 * 用户管理编辑
 * @param props
 * @constructor
 */
const Edit: React.FC<userEditPros> = (props) => {
  const { visible, editCallback, detailData } = props;
  const [form] = Form.useForm();
  // const uploadHeaders = { Authorization: `${localStorage.getItem('token')}` };
  // const [fileUrl, setFileUrl]: any = useState(
  //   detailData && detailData.photo ? detailData.photo : '',
  // );
  // const [loading, setLoading] = useState(false);
  const [roleList, setRoleList] = useState([]);
  // const [selectList, setSelectList] = useState([]);
  const [areaList, setAreaList] = useState([]);
  const [isCurrent, setIsCurrent] = useState(false);

  // const getBase64 = (img: any) => {
  //   const reader = new FileReader();
  //   reader.readAsDataURL(img);
  //   reader.onloadend = () => {
  //     const url = reader.result;
  //     setFileUrl(url);
  //   };
  // };

  useEffect(() => {
    // 编辑时
    if (detailData) {
      infoQuery().then((res) => {
        if (res?.code === 0) {
          // 判断当前编辑用户数据和登录账号是否为同一个
          // 同一个则直接显示用户数据中user_role（角色名称）和parent_name（所属名称）
          if (res.data.record_id === detailData.record_id) {
            setIsCurrent(true);
            const user_role_list: any = [];
            const obj = {
              name: '',
              record_id: '',
            };
            detailData.user_role.forEach((el: { role_id: string; role_name: string }) => {
              obj.name = el.role_name;
              obj.record_id = el.role_id;
              user_role_list.push(obj);
            });
            setRoleList(user_role_list);
          } else {
            // 角色列表
            queryRoleList({ q: 'list' }).then((item) => {
              if (item.code === 0) {
                setRoleList(item.data.list);
              }
            });
          }
        }
      });

      // 编辑时，所属地区根据角色id回显数据
      // const data = [...detailData?.user_role].sort((a: any, b: any) => b.level - a.level);
      // if (data && data.length) {
      //   const param = {
      //     q: 'list',
      //     role_id: data[0].role_id,
      //     user_id: detailData.record_id,
      //   };
      //   // 根据角色id请求用户列表接口 保证所属名称字段编辑时回显
      //   queryRoleUser(param).then((item) => {
      //     if (item.code === 0) {
      //       setSelectList(item?.data || []);
      //     }
      //   });
      // }
    } else {
      // 新增
      // 角色列表
      queryRoleList({ q: 'list' }).then((res) => {
        if (res.code === 0) {
          setRoleList(res.data.list);
        }
      });
    }

    //  地区列表
    queryTreeList({ q: 'tree', level: '3' }).then((res) => {
      if (res && res.code === 0) {
        setAreaList(res.data.list || []);
      }
    });
  }, []);

  // const handleLevel = (values: any) => {
  //   const data: any = roleList.filter((option: { record_id: string }) =>
  //     values.includes(option.record_id),
  //   );
  //   return [...data].sort((a: any, b: any) => b.level - a.level);
  // };

  // 角色选择
  // const onRoleChange = (selectedValues: any) => {
  //   // 切换角色时，所属名称要清空重新选择
  //   form.setFieldsValue({ parent_id: '' });
  //   const sortedData = handleLevel(selectedValues);
  //   if (sortedData && sortedData.length > 0) {
  //     const maxLevelObject = sortedData[0];
  //     const param = {
  //       q: 'list',
  //       role_id: maxLevelObject.record_id,
  //     };
  //     queryRoleUser(param).then((res) => {
  //       if (res.code === 0) {
  //         setSelectList(res?.data || []);
  //       }
  //     });
  //   } else {
  //     setSelectList([]);
  //   }
  // };

  // const filesProps: UploadProps = {
  //   maxCount: 1,
  //   action: '/web/v1/files',
  //   headers: uploadHeaders,
  //   listType: 'picture-card',
  //   showUploadList: false,
  //   onChange(info) {
  //     if (info.file.status === 'uploading') {
  //       setLoading(true);
  //       return;
  //     }
  //     if (info.file.status === 'done') {
  //       setLoading(false);
  //       getBase64(info.file.originFileObj);
  //     } else if (info.file.status === 'error') {
  //       setLoading(false);
  //       message.error('文件上传失败');
  //     }
  //   },
  // };

  /**
   * 确定
   */
  const onOk = () => {
    form.validateFields().then((values) => {
      if (values) {
        const data = { ...values };
        if (values?.photo) {
          data.photo = values?.photo?.file?.response?.data?.url;
        }
        if (values?.password) {
          data.password = md5(values.password);
        }
        if (values?.role_id) {
          const user_role: { role_id: any }[] = [];
          values?.role_id.forEach((el: any) => {
            user_role.push({ role_id: el });
          });
          data.user_role = user_role;
          delete data.role_id;
        }
        // if (values?.area) {
        //   data.province = values.area[0];
        //   data.city = values.area[1];
        //   data.district = values.area[2];
        //   delete data.area;
        // }
        if (values.districts) {
          const arr: any[] = [];
          values.districts.forEach((el: any) => {
            arr.push({
              district_id: el[1],
            });
          });
          data.districts = arr;
        }
        if (values?.parent_id) {
          data.parent_id = values?.parent_id;
        }
        if (detailData) {
          data.record_id = detailData.record_id;
          //  编辑
          editUser(data)
            .then((res) => {
              if (res.code === 0) {
                message.success('编辑成功');
                editCallback();
              } else {
                message.error(res?.message);
                editCallback();
              }
            })
            .catch((e) => {
              message.error(e?.message);
              editCallback();
            });
        } else {
          // 新增
          createUser(data)
            .then((res) => {
              if (res.code === 0) {
                message.success('保存成功');
                editCallback();
              } else {
                message.error(res?.message);
                editCallback();
              }
            })
            .catch((e) => {
              message.error(e?.message);
              editCallback();
            });
        }
      }
    });
  };

  /**
   * 取消
   */
  const onCancel = () => {
    editCallback();
  };

  const formItemLayout = {
    labelCol: {
      span: 6,
    },
    wrapperCol: {
      span: 16,
    },
  };

  const formItemLayoutTwo = {
    labelCol: {
      span: 3,
    },
    wrapperCol: {
      span: 21,
    },
  };

  // const uploadButton = (
  //   <div>
  //     {loading ? <LoadingOutlined /> : <PlusOutlined />}
  //     <div className="ant-upload-text">上传</div>
  //   </div>
  // );

  return (
    <Modal
      title={`${detailData ? '编辑' : '新增'}`}
      open={visible}
      onOk={onOk}
      onCancel={onCancel}
      width={800}
    >
      <Form form={form}>
        <Row>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              name="user_name"
              label="用户姓名"
              rules={[{ required: true, message: '请输入用户姓名' }]}
              initialValue={detailData?.user_name || ''}
            >
              <Input placeholder="请输入用户姓名" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item {...formItemLayout} name="password" label="密码">
              <Input type="password" placeholder="请输入密码" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              name="phone"
              label="手机号"
              rules={[
                { required: true, message: '请输入手机号' },
                {
                  pattern:
                    /^1((34[0-8])|(8\d{2})|(([35][0-35-9]|4[579]|66|7[35678]|9[1389])\d{1}))\d{7}$/,
                  message: '请输入正确的手机号',
                },
              ]}
              initialValue={detailData?.phone || ''}
            >
              <Input placeholder="请输入手机号" />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              name="company"
              label="公司名称"
              initialValue={detailData?.company || ''}
            >
              <Input placeholder="请输入公司名称" />
            </Form.Item>
          </Col>
          <Col span={24}>
            <Form.Item
              {...formItemLayoutTwo}
              name="role_id"
              label="角色名称"
              rules={[{ required: true, message: '请选择角色名称' }]}
              initialValue={
                detailData && detailData?.user_role && detailData?.user_role.length
                  ? detailData?.user_role?.map((item: any) => item.role_id)
                  : []
              }
            >
              <Checkbox.Group
                options={roleList.map((option: { record_id: string; name: string }) => ({
                  label: option.name,
                  value: option.record_id,
                  record_id: option.record_id,
                }))}
                disabled={isCurrent}
                // onChange={onRoleChange}
              />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              name="quota"
              label="配额"
              rules={[{ required: true, message: '请输入配额' }]}
              initialValue={detailData?.quota || ''}
            >
              <InputNumber min={0} placeholder="请输入配额" style={{ width: '100%' }} />
            </Form.Item>
          </Col>
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              name="districts"
              label="地区"
              rules={[{ required: true, message: '请选择地区' }]}
              initialValue={detailData?.districts || []}
            >
              <Cascader
                style={{ width: '100%' }}
                options={areaList}
                multiple
                placeholder="请选择地区"
                maxTagCount="responsive"
                fieldNames={{ label: 'name', value: 'record_id', children: 'children' }}
              />
            </Form.Item>
          </Col>
          {/*<Col span={24}>*/}
          {/*  <Form.Item*/}
          {/*    {...formItemLayoutTwo}*/}
          {/*    name="parent_id"*/}
          {/*    label="上级用户"*/}
          {/*    initialValue={detailData?.parent_id || ''}*/}
          {/*  >*/}
          {/*    <Select placeholder="请选择所属名称" disabled={isCurrent}>*/}
          {/*      {selectList && selectList.length*/}
          {/*        ? selectList.map(*/}
          {/*            (res: { user_name: string; record_id: string; parent_id: string }) => {*/}
          {/*              return (*/}
          {/*                <Select.Option key={res.record_id} value={res.record_id}>*/}
          {/*                  {res?.user_name}*/}
          {/*                </Select.Option>*/}
          {/*              );*/}
          {/*            },*/}
          {/*          )*/}
          {/*        : null}*/}
          {/*    </Select>*/}
          {/*  </Form.Item>*/}
          {/*</Col>*/}
          {/*<Col span={24}>*/}
          {/*  <Form.Item*/}
          {/*    {...formItemLayoutTwo}*/}
          {/*    name="area"*/}
          {/*    label="所属地区"*/}
          {/*    initialValue={*/}
          {/*      detailData?.province || detailData?.city || detailData?.district*/}
          {/*        ? [detailData?.province, detailData?.city, detailData?.district]*/}
          {/*        : []*/}
          {/*    }*/}
          {/*  >*/}
          {/*    <Cascader*/}
          {/*      options={areaList}*/}
          {/*      placeholder="请选择所属地区"*/}
          {/*      fieldNames={{ label: 'name', value: 'name', children: 'children' }}*/}
          {/*    />*/}
          {/*  </Form.Item>*/}
          {/*</Col>*/}
          {/*<Col span={12}>*/}
          {/*  <Form.Item {...formItemLayout} name="photo" label="头像" initialValue={[]}>*/}
          {/*    <Upload {...filesProps}>*/}
          {/*      {fileUrl === '' ? (*/}
          {/*        uploadButton*/}
          {/*      ) : (*/}
          {/*        <img src={fileUrl} alt="data" style={{ width: '100%' }} />*/}
          {/*      )}*/}
          {/*    </Upload>*/}
          {/*  </Form.Item>*/}
          {/*</Col>*/}
        </Row>
      </Form>
    </Modal>
  );
};
export default Edit;
