import React, { useEffect, useState } from 'react';
import {
  Cascader,
  Checkbox,
  Col,
  Form,
  Input,
  InputNumber,
  message,
  Modal,
  Row,
  Select,
} from 'antd';
import { createUser, editUser, queryTreeList, queryUserList } from '@/services/setting';
import md5 from 'js-md5';
import { queryRoleList } from '@/services/role';

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 [roleList, setRoleList] = useState([]);
  const [areaList, setAreaList] = useState([]);
  const [dealerList, setDealerList] = useState([]);
  const [roleCode, setRoleCode]: any = useState([]);

  useEffect(() => {
    if (detailData) {
      //  编辑时，根据角色判断是否显示配额和所属经销商
      const arr: any[] = [];
      detailData.user_role.forEach((el: any) => {
        arr.push(el.role_code);
      });
      setRoleCode(arr);
    }

    //  经销商列表
    queryUserList({ q: 'list', code_str: '21' }).then((res) => {
      if (res && res.code === 0) {
        setDealerList(res.data || []);
      }
    });

    // 角色列表
    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 onRoleChange = (e: any, code: string) => {
    const {
      target: { checked },
    } = e;
    let arr: any = [...roleCode];
    if (checked) {
      if (!roleCode.includes(code)) {
        arr.push(code);
      }
    } else {
      arr = arr.filter((item: any) => item !== code);
    }
    setRoleCode(arr);
  };

  /**
   * 确定
   */
  const onOk = () => {
    form.validateFields().then((values) => {
      if (values) {
        const data = { ...values };
        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.districts) {
          const arr: any[] = [];
          values.districts.forEach((el: any) => {
            arr.push({
              province_id: el[0],
              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,
    },
  };

  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>
                {roleList && roleList.length
                  ? roleList.map((res: any) => {
                      return (
                        <Checkbox
                          key={res.record_id}
                          value={res.record_id}
                          onChange={(e) => onRoleChange(e, res.code)}
                        >
                          {res.name}
                        </Checkbox>
                      );
                    })
                  : null}
              </Checkbox.Group>
            </Form.Item>
          </Col>
          {roleCode.includes('21') || roleCode.includes('22') ? (
            <Col span={12}>
              <Form.Item
                {...formItemLayout}
                name="quota"
                label="配额"
                initialValue={detailData?.quota || ''}
                rules={[{ required: true, message: '请输入配额' }]}
              >
                <InputNumber min={0} placeholder="请输入配额" style={{ width: '100%' }} />
              </Form.Item>
            </Col>
          ) : null}
          <Col span={12}>
            <Form.Item
              {...formItemLayout}
              name="districts"
              label="地区"
              initialValue={
                detailData?.districts.map((item: any) => [
                  item.province_id,
                  ...(item.district_id ? [item.district_id] : []),
                ]) || []
              }
            >
              <Cascader
                style={{ width: '100%' }}
                options={areaList}
                multiple
                placeholder="请选择地区"
                maxTagCount="responsive"
                fieldNames={{ label: 'name', value: 'record_id', children: 'children' }}
              />
            </Form.Item>
          </Col>
          {roleCode.includes('22') ? (
            <Col span={12}>
              <Form.Item
                {...formItemLayout}
                name="parent_id"
                label="所属经销商"
                initialValue={detailData?.parent_id || undefined}
                rules={[{ required: true, message: '请选择所属经销商' }]}
              >
                <Select placeholder="请选择所属经销商">
                  {dealerList && dealerList.length
                    ? dealerList.map((res: any) => {
                        return (
                          <Select.Option key={res.record_id} value={res.record_id}>
                            {res.user_name}
                          </Select.Option>
                        );
                      })
                    : null}
                </Select>
              </Form.Item>
            </Col>
          ) : null}
        </Row>
      </Form>
    </Modal>
  );
};
export default Edit;
