import React, { useEffect, useState } from "react";
import { Modal, Form, Select, InputNumber, message, Input, Button, Radio } from "antd";
import { useStore } from "../index";
import _ from "lodash";
import Rule1 from "@/pages/performance/CompensateGroupConfig/components/Rule1";
import { EvaGroupSetteing } from "@/pages/performance/EvaGroupSetting/interface";
import SingleAmount from "@/pages/performance/CompensateGroupConfig/EditComfirm/components/SingleAmount";
import TotalAmountSal from "./TotalAmountSal";
import FixedCommission from "@/pages/performance/CompensateGroupConfig/EditComfirm/components/FixedCommission";
import CommissionParamsSal from "./CommissionParamsSal";
import LadderParamsSal from "./LadderParamsSal";
import RankModal from "./RankModal";
import { Any } from "currency.js";
import CondsSal from "./CondsSal";

const Option = Select.Option;
interface Props {
  visible: boolean;
  onCancel: Function;
  onOk: (vales: any) => void;
  currentItem: EvaGroupSetteing.Rewards;
  indicatorsList?: any[];
  postId?: number;
  shopIds?: string;
  scopeType: number;
}

export default function CreateModal(props: Props) {
  const [form] = Form.useForm();
  const {
    ladderParamAlias,
    setLadderParamAlias,
    commissionParamAlias,
    setCommissionParamAlias,
    preconditionAliasSal,
    setPreconditionAliasSal,
    calType,
    setCalType,
  } = useStore();
  const { visible, onCancel, onOk, currentItem, indicatorsList = [], postId, shopIds, scopeType } = props;

  // 是否为百分比
  const [isPercent, setIsPercent] = useState<number>(0);

  // 判断占比相加是否为100
  const [isHundred, setIsHundred] = useState(false);
  const [isHundredLadder, setIsHundredLadder] = useState(false);
  // 显示前置条件
  const [condsVisible, setCondsVisible] = useState(false);

  const [id, setItemId] = useState<number>();
  
  useEffect(() => {
    if (visible && currentItem.name) {
      setLadderParamAlias(currentItem.ladderParamAlias);
      setCommissionParamAlias(currentItem.commissionParamAlias);
      setPreconditionAliasSal(currentItem.preconditionAlias);
      //编辑时存储当前薪酬项目的计算方式
      setCalType(currentItem.calMethod);
      // if (currentItem.settings[0].stairKeyDesc !== undefined && currentItem.calMethod === 4) {
      //   setFixData(currentItem.settings);
      // }
      if (currentItem.conds && currentItem.conds.length > 0) {
        setCondsVisible(true);
      } else {
        setCondsVisible(false);
      }
      form.setFieldsValue({
        ...currentItem,
      });
    }
    if (!currentItem.name) {
      setCondsVisible(false);
    }
  }, [visible]);

  // 保存Modal
  function handSubmit(fieldsValue: any) {
    const pa: any = fieldsValue;
    // 校验标准分不能大于绩效分值
    // if (id) {
    //   pa.id = id;
    // } else {
    //   pa.id = pa.name;
    // }
    if (pa?.ladderParams && pa?.ladderParams.length > 0) {
      pa.ladderParamAlias = ladderParamAlias;
    }
    if (pa?.commissionParams && pa?.commissionParams.length > 0) {
      pa.commissionParamAlias = commissionParamAlias;
    }
    if (pa?.conds && pa?.conds.length > 0) {
      pa.preconditionAlias = preconditionAliasSal;
    }
    let hundred = 0;
    let ladderHundred = 0;
    //设置sort
    if (pa?.commissionParams && pa?.commissionParams.length > 0) {
      pa?.commissionParams.forEach((item: any, index: number) => {
        Object.assign(item, { sort: index + 1 });
      });
      hundred = pa?.commissionParams.reduce((data: number, item: any) => {
        return data + item.proportion;
      }, 0);
    }
    if (pa?.ladderParams && pa?.ladderParams.length > 0) {
      pa?.ladderParams.forEach((item: any, index: number) => {
        Object.assign(item, { sort: index + 1 });
      });
      ladderHundred = pa?.ladderParams.reduce((data: number, item: any) => {
        return data + item.proportion;
      }, 0);
      if (isPercent == 0) {
        pa.laddersType = currentItem.laddersType;
      } else {
        pa.laddersType = isPercent;
      }
    }
    if (!pa?.ladderParams || pa?.ladderParams.length === 0) {
      pa.laddersType = 2;
    }
    if (pa?.conds) {
      pa?.conds.forEach((item: any, index: number) => {
        Object.assign(item, { sort: index + 1 });
      });
    }
    if (pa?.ladderParams && pa?.ladderParams.length > 0 && pa?.commissionParams && pa?.commissionParams.length > 0) {
      if (hundred === 100 && ladderHundred === 100) {
        setIsHundred(false);
        setIsHundredLadder(false);
        onOk(pa);
        console.log("100pa", pa);
        onCancel && onCancel();
      } else if (hundred === 100 && ladderHundred !== 100) {
        setIsHundred(false);
        setIsHundredLadder(true);
      } else if (hundred !== 100 && ladderHundred === 100) {
        setIsHundred(true);
        setIsHundredLadder(false);
      } else {
        setIsHundred(true);
        setIsHundredLadder(true);
      }
    } else if (!pa?.ladderParams && pa?.commissionParams && pa?.commissionParams.length > 0) {
      if (hundred === 100) {
        setIsHundred(false);
        onOk(pa);
        console.log("100pa", pa);
        onCancel && onCancel();
      } else {
        setIsHundred(true);
      }
    } else if (pa?.ladderParams && pa?.commissionParams && pa?.commissionParams.length === 0) {
      if (ladderHundred === 100) {
        setIsHundredLadder(false);
        onOk(pa);
        console.log("100pa", pa);
        onCancel && onCancel();
      } else {
        setIsHundredLadder(true);
      }
    } else if (pa?.ladderParams && pa?.commissionParams == undefined) {
      if (ladderHundred === 100) {
        setIsHundredLadder(false);
        onOk(pa);
        console.log("100pa", pa);
        onCancel && onCancel();
      } else {
        setIsHundredLadder(true);
      }
    } else if (pa?.commissionParams == undefined) {
      setIsHundred(false);
      onOk(pa);
      console.log("100pa", pa);
      onCancel && onCancel();
    } else if (pa?.commissionParams && pa?.commissionParams.length == 0) {
      setIsHundred(false);
      onOk(pa);
      console.log("100pa", pa);
      onCancel && onCancel();
    }
  }

  return (
    <Modal
      title={`${currentItem.name ? "编辑" : "新增"}考评奖惩`}
      visible={visible}
      maskClosable={false}
      afterClose={() => {
        form.resetFields();
        onCancel();
      }}
      onCancel={() => onCancel()}
      onOk={form.submit}
      width={1200}
    >
      <Form
        form={form}
        labelCol={{ span: 4 }}
        wrapperCol={{ span: 20 }}
        onFinish={handSubmit}
        initialValues={{
          ladders: [{ lower: 0, money: 0, key: 0 }],
        }}
      >
        <Form.Item name="name" label="考评奖惩指标名称" rules={[{ required: true, message: "请输入指标名称" }]}>
          <Input placeholder="请输入指标名称" />
        </Form.Item>

        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) => prevValues.calMethod !== currentValues.calMethod}
        >
          {({ getFieldValue }) => {
            return (
              <Form.Item name="calMethod" label="计算方式" rules={[{ required: true, message: "请选择计算方式" }]}>
                <Select
                  placeholder="选择计算方式"
                  onChange={(value) => {
                    const _type = value;
                    setCalType(_type);
                    console.log(calType);
                  }}
                >
                  <Option value={1} key={1}>
                    排名正负激励
                  </Option>
                  <Option value={2} key={2}>
                    固定值
                  </Option>
                  <Option value={3} key={3}>
                    阶梯
                  </Option>
                  <Option value={4} key={4}>
                    总金额占比
                  </Option>
                  <Option value={5} key={5}>
                    阶梯翻倍
                  </Option>
                </Select>
              </Form.Item>
            );
          }}
        </Form.Item>

        <div style={{ marginLeft: 95, marginBottom: 20 }}>
          <span>是否添加前置条件设置：</span>
          <Radio.Group
            onChange={(e) => {
              setCondsVisible(e.target.value);
            }}
            value={condsVisible}
          >
            <Radio value>是</Radio>
            <Radio value={false}>否</Radio>
          </Radio.Group>
        </div>
        {condsVisible && (
          <Form.Item name="conds" label="前置条件">
            <CondsSal postId={postId} shopIds={shopIds} setItemId={setItemId} scopeType={scopeType} />
          </Form.Item>
        )}
        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) => prevValues.calMethod !== currentValues.calMethod}
        >
          {({ getFieldValue }) => {
            const caculateType = getFieldValue("calMethod");
            if (caculateType !== 1) {
              return (
                <>
                  <Form.Item
                    name="commissionParams"
                    label="提成指标"
                    rules={[{ required: caculateType == 2 || caculateType == 4, message: "请增加提成指标" }]}
                  >
                    <CommissionParamsSal
                      postId={postId}
                      shopIds={shopIds}
                      setItemId={setItemId}
                      isHundred={isHundred}
                      scopeType={scopeType}
                    />
                  </Form.Item>
                </>
              );
            } else {
              return null;
            }
          }}
        </Form.Item>
        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) => prevValues.calMethod !== currentValues.calMethod}
        >
          {({ getFieldValue }) => {
            const caculateType = getFieldValue("calMethod");
            if (caculateType == 1) {
              return (
                <>
                  <Form.Item
                    name="ladderParams"
                    label="台阶条件指标"
                    rules={[{ required: true, message: "请增加台阶条件指标" }]}
                  >
                    <LadderParamsSal
                      postId={postId}
                      shopIds={shopIds}
                      setItemId={setItemId}
                      isHundredLadder={isHundredLadder}
                      scopeType={scopeType}
                    />
                  </Form.Item>
                  <Form.Item name="rankType" label="排名方式" rules={[{ required: true, message: "请选择排名方式" }]}>
                    <Radio.Group>
                      <Radio value={1}>按固定值 </Radio>
                      <Radio value={2}>按比例</Radio>
                    </Radio.Group>
                  </Form.Item>
                  {/* <Form.Item name="rankOrderType" label="排名顺序" rules={[{ required: true, message: "请选择排名顺序" }]}>
                    <Radio.Group>
                      <Radio value={1}>正数</Radio>
                      <Radio value={2}>倒数</Radio>
                    </Radio.Group>
                  </Form.Item> */}
                  <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, currentValues) => prevValues.rankType !== currentValues.rankType}
                  >
                    {({ getFieldValue }) => {
                      const rankType = getFieldValue("rankType");
                      if (rankType == 1) {
                        setIsPercent(1);
                      } else {
                        setIsPercent(2);
                      }
                      return null;
                    }}
                  </Form.Item>
                  <Form.Item
                    noStyle
                    shouldUpdate={(prevValues, currentValues) => prevValues.rankType !== currentValues.rankType}
                  >
                    {({ getFieldValue }) => {
                      const rankType = getFieldValue("rankType");
                      if (rankType == 1 && !currentItem.ladders) {
                        form.setFieldValue("ladders", [{ lower: 1, money: 0, key: 0, rankOrderType: 1 }]);
                      } else if (rankType == 2 && !currentItem.ladders) {
                        form.setFieldValue("ladders", [{ lower: 0, money: 0, key: 0, rankOrderType: 1 }]);
                      }
                      return (
                        <Form.Item
                          name="ladders"
                          label="排名设置"
                          rules={[{ required: true, message: "请配置排名" }]}
                          style={{ width: "100%" }}
                        >
                          <RankModal
                            visible
                            isPercent={isPercent}
                            laddersType={currentItem?.laddersType}
                            calType={calType}
                            rankType={rankType}
                          />
                        </Form.Item>
                      );
                    }}
                  </Form.Item>
                </>
              );
            } else if (caculateType == 2 || caculateType == 4) {
              return (
                <>
                  <Form.Item
                    label="金额"
                    name="money"
                    rules={[{ required: true, message: "请输入金额" }]}
                    style={{ marginLeft: 0 }}
                  >
                    <InputNumber style={{ width: 960 }} addonAfter="元" />
                  </Form.Item>
                </>
              );
            } else if (caculateType == 3 || caculateType == 5) {
              return (
                <>
                  <Form.Item
                    name="ladderParams"
                    label="台阶条件指标"
                    rules={[{ required: true, message: "请增加台阶条件指标" }]}
                  >
                    <LadderParamsSal
                      postId={postId}
                      shopIds={shopIds}
                      setItemId={setItemId}
                      isHundredLadder={isHundredLadder}
                      scopeType={scopeType}
                    />
                  </Form.Item>
                </>
              );
            }
            return null;
          }}
        </Form.Item>

        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) => prevValues.ladderParams !== currentValues.ladderParams}
        >
          {({ getFieldValue }) => {
            const ladderParams = getFieldValue("ladderParams");
            const calMethod = getFieldValue("calMethod");
            if (ladderParams && ladderParams.length > 0 && (calMethod == 3 || calMethod == 5)) {
              console.log("ladderParams", ladderParams);
              if (ladderParams.length > 1) {
                setIsPercent(2);
              } else if (ladderParams[0].targetValue) {
                setIsPercent(2);
              } else if (ladderParams[0].dataType === 2) {
                setIsPercent(2);
              } else if (ladderParams[0].dataType === 1 || ladderParams[0].dataType === 3) {
                console.log("hasvdhjasvhdj");
                setIsPercent(1);
              }
            }
            return null;
          }}
        </Form.Item>
        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) => prevValues.calMethod !== currentValues.calMethod}
        >
          {({ getFieldValue }) => {
            const caculateType = getFieldValue("calMethod");
            //阶梯（总）
            if (caculateType == 3 || caculateType == 5) {
              if (caculateType == 3 && !currentItem.ladders) {
                form.setFieldValue("ladders", [{ lower: 0, money: 0, key: 0 }]);
              } else if (caculateType == 5 && !currentItem.ladders) {
                form.setFieldValue("ladders", [{ lower: 0, money: 0, capMoney: 0, key: 0 }]);
              }
                return (
                  <>
                    <Form.Item
                      name="ladders"
                      label="阶梯条件"
                      rules={[{ required: true, message: "请配置阶梯" }]}
                      style={{ width: "100%" }}
                    >
                      <TotalAmountSal
                        visible
                        isPercent={isPercent}
                        laddersType={currentItem.laddersType}
                        calType={calType}
                      />
                    </Form.Item>
                  </>
                );
            }
            return null;
          }}
        </Form.Item>
      </Form>
    </Modal>
  );
}
