import _ from "lodash";
import React, { forwardRef, useImperativeHandle, useCallback } from "react";
import { Form, Input, Radio, Row, DatePicker, Icon } from "antd";
import styled from "styled-components";
import ImageUploader from "./widget/ImageUploader";
import ResumesUploader from "./widget/ResumesUploader";
import JobExpect from "./widget/JobExpect";
import EduItem from "./widget/EduItem";
import WorkItem from "./widget/WorkItem";
import { FormCtx } from "./Form";
import { AddButton } from "./widget/Button";
import { useSet } from "../util/hooks";
import { genUuid } from "../data/genUuid";
import { mapPropsToFields } from "../data/mapResumeData";
import moment from "moment";

const Label = styled.div`
  &::before {
    content: ${(p) => (p.required ? '"*"' : '""')};
    color: ${(p) => (p.required ? "red" : "black")};
  }
  &::after {
    content: "：";
  }
  margin-bottom: 5px;
  font-size: 16px;
  font-family: MicrosoftYaHeiSemibold;
  color: rgba(51, 51, 51, 1);
`;
const Tip = styled.div`
  font-size: 12px;
  font-family: MicrosoftYaHei;
  color: rgba(136, 136, 136, 1);
  margin-left: 10px;
`;

export default Form.create({ mapPropsToFields })(
  forwardRef(({ form, attachment_name, logo_url, attachment_url, attachment_id }, ref) => {
    const {
      getFieldDecorator,
      validateFields,
      getFieldValue,
      setFields,
      getFieldsValue
    } = form;
    const { set: eduSet, add: eduAdd, remove: eduRm } = useSet();
    const { set: wkSet, add: wkAdd, remove: wkRm } = useSet();
    const addEdu = useCallback(() => {
      const uuid = genUuid();
      eduAdd(uuid);
      return uuid;
    }, []);
    const addWk = useCallback(() => {
      const uuid = genUuid();
      wkAdd(uuid);
      return uuid;
    }, []);
    const set = useCallback((education, experience) => {
      const object = {};
      if (experience !== undefined) {
        experience.forEach((exp) => {
          const id = addWk();
          ["company", "desc"].forEach((k) => {
            object[`experience[${id}].${k}`] = { value: exp[k] };
          });
          ["begin_on", "end_on"].forEach((k) => {
            object[`experience[${id}].${k}`] = { value: moment(exp[k]) };
          });
        });
      }
      if (education !== undefined) {
        let isFirst = true;
        education.forEach((edu) => {
          const id = isFirst ? "base" : addEdu();
          ["edu_bg", "edu_category", "major", "school"].forEach((k) => {
            object[`education[${id}].${k}`] = { value: edu[k] };
          });
          ["begin_on", "end_on"].forEach((k) => {
            object[`education[${id}].${k}`] = { value: moment(edu[k]) };
          });
          isFirst = false;
        });
      }
      setTimeout(() => {
        setFields(object);
      }, 1000);
    }, []);
    const genVerArr = useCallback(() => {
      const genWk = (key) =>
        ["begin_on", "end_on", "company", "desc"].map(
          (k) => `experience[${key}].${k}`
        );
      const genEdu = (key) =>
        ["begin_on", "end_on", "edu_bg", "edu_category", "major", "school"].map(
          (k) => `education[${key}].${k}`
        );
      const field = [
        "name",
        "sex",
        "logo",
        "birth_on",
        "mobile",
        "evaluate",
        "attachment_id",
        "job_position",
        "city",
        "salary",
        "job_category",
        "job_year",
      ];
      const baseEdu = genEdu("base");
      const wk = _.flatten(Array.from(wkSet.keys()).map(genWk));
      const edu = _.flatten(Array.from(eduSet.keys()).map(genEdu));
      return _.concat(wk, edu, field, baseEdu);
    }, []);
    useImperativeHandle(ref, () => ({
      verify: (callback) => {
        validateFields(genVerArr(), callback);
      },
      set,
    }));
    const helper = useCallback(
      (label, name, rules, widget, isRequired = true) => (
        <React.Fragment>
          <Label required={isRequired}>{label}</Label>
          <Form.Item>
            {getFieldDecorator(name, { rules, validateFirst: true })(widget)}
          </Form.Item>
        </React.Fragment>
      ),
      []
    );
    return (
      <FormCtx.Provider value={{ getFieldDecorator, getFieldValue }}>
        <Form>
          {helper(
            "姓名",
            "name",
            [
              { max: 60, message: "超过60字符" },
              { required: true, message: "请输入姓名" },
              { whitespace: true, message: "不能全空" },
            ],
            <Input placeholder="请输入姓名" style={{ width: "534px" }} />
          )}
          {helper(
            "性别",
            "sex",
            [{ required: true, message: "请选择性别" }],
            <Radio.Group>
              <Radio value="男">男</Radio>
              <Radio value="女">女</Radio>
            </Radio.Group>
          )}
          <Row type="flex" justify="start" align="middle">
            <Label>照片上传</Label>
            <Tip>只支持JPG,JPEG格式,大小不要超过2MB，建议使用证件照</Tip>
          </Row>
          {getFieldDecorator("logo", {})(<ImageUploader logo_url={logo_url} />)}
          {helper(
            "出生日期",
            "birth_on",
            [{ required: true, message: "请选择日期" }],
            <DatePicker placeholder="请选择日期" disabledDate={(m) => m > moment()} />
          )}
          {helper(
            "手机号",
            "mobile",
            [
              { required: true, message: "请输入手机号" },
              { min: 11, message: "号码不正确" },
              { max: 11, message: "号码不正确" },
              { pattern: /^\d+$/, message: "请输入数字" },
            ],
            <Input placeholder="请输入手机号" style={{ width: "534px" }} />
          )}
          {helper(
            "参加工作时间",
            "job_year",
            [],
            <DatePicker.MonthPicker placeholder="请选择日期" />,
            false
          )}
          <Label required>求职意向</Label>
          <JobExpect />
          <Label required>教育经历</Label>
          <EduItem nameKey="base" />
          {Array.from(eduSet.values()).map((k) => (
            <EduItem
              nameKey={k}
              key={k}
              onDelete={() => {
                eduRm(k);
              }}
            />
          ))}
          <AddButton onClick={addEdu}>
            <Icon type="plus" />
            添加教育经历
          </AddButton>
          <Label>工作/实习经历</Label>
          {Array.from(wkSet.values()).map((k) => (
            <WorkItem
              nameKey={k}
              key={k}
              onDelete={() => {
                wkRm(k);
              }}
            />
          ))}
          <AddButton onClick={addWk}>
            <Icon type="plus" />
            添加工作经验
          </AddButton>
          {helper(
            "自我评价",
            "evaluate",
            [{ max: 5000, message: "超过5000字符" }],
            <Input.TextArea
              placeholder="请输入自我评价"
              autoSize={{ minRows: 4, maxRows: 4 }}
            />,
            false
          )}
          <Row type="flex" justify="start" align="middle">
            <Label>简历上传</Label>
            <Tip>（上传简历可以提高应聘成功率）</Tip>
          </Row>
          {getFieldDecorator("attachment_id", { rules: [] })(
            <ResumesUploader
              attachment_name={attachment_name}
              attachment_url={attachment_url}
              attachment_id={attachment_id}
            />
          )}
        </Form>
      </FormCtx.Provider>
    );
  })
);
