/* eslint-disable no-return-assign */
/* eslint-disable no-return-assign */
import React, { useEffect, useState } from "react";
import { Modal, Form, Select, InputNumber, message, Spin, Radio, Input, Button, DatePicker } from "antd";
import { saveRewardsListApi } from "../RewardsList/api";
import { useStore } from "../index";
import _ from "lodash";
import useInitail from "@/hooks/useInitail";
import { EvaGroupSetteing } from "@/pages/performance/EvaGroupSetting/interface";
import * as api from "@/pages/performance/KpiGroupSetting/EditComfirm/api";
import ShopSelectNew from "@/components/ShopSelectNew";
import PersonModal from "@/pages/performance/KpiGroupSetting/components/PersonModal";
import { transformDTO } from "../entity";
import IndivatorsTable from "./IndivatorsTable";
import RewardsTableSal from "./RewardsTableSal";
import moment from "moment";
import { getManagerRoleListApi } from "@/common/api";

const Option = Select.Option;
const { RangePicker } = DatePicker;
interface Props {
  visible: boolean;
  onCancel: Function;
  onOk: (vales: any) => void;
  evaItem: EvaGroupSetteing.EvalGroups;
  scopeType: number;
  setScopeType: Function;
}

export default function AddIndicatorsModal(props: Props) {
  const { postList, readOnly } = useStore();
  const [roleList, setRoleList] = useState<any>([]);

  const { visible, onCancel, onOk, evaItem, scopeType, setScopeType } = props;

  const [form] = Form.useForm();
  // 选择岗位id
  const [postId, setPostId] = useState<number>();

  // 门店列表
  const [shopList, setShopList] = useState<EvaGroupSetteing.ShopList[]>([]);

  // 人员查看模块
  const [personModal, setPersonModal] = useState<EvaGroupSetteing.Person>({
    visible: false,
    postId: undefined,
    shopIds: "",
  });

  // visible变化时（修改等）
  useEffect(() => {
    getRoleList();
    if (visible && evaItem.name) {
      if (evaItem.shop) {
        const shopIds = evaItem.shop.map((item) => item.value);
        setPersonModal({
          shopIds: shopIds.join(","),
          visible: false,
        });
      }
      if (evaItem.shop && evaItem.post) {
        const shopIds = evaItem.shop.map((item) => item.value);
        const postId = evaItem.post.value;
        setPersonModal({
          postId,
          shopIds: shopIds.join(","),
          visible: false,
        });
      }
      console.log("evaItem", evaItem);
      form.setFieldsValue({
        ...evaItem,
      });
    }
  }, [visible]);

  // 查询门店
  useEffect(() => {
    if (evaItem.post) {
      getDealerList(evaItem.post.value);
    }
  }, [evaItem]);
  console.log("shopList", shopList);

  // 查询管理角色
  function getRoleList() {
    getManagerRoleListApi()
      .then((res) => {
        setRoleList(res.data || []);
      })
      .catch((e) => {
        message.error(e.message);
      });
  }

  // 根据岗位查门店
  function getDealerList(postId: number) {
    api
      .queryShopByPost(postId)
      .then((res) => {
        setShopList(res.data || []);
      })
      .catch((e) => {
        message.error(e.message);
      });
  }
  // 人员查看
  const personView = () => {
    if (!personModal.postId) {
      message.error("请选择岗位");
      return;
    }
    if (!personModal.shopIds) {
      message.error("请选择门店");
      return;
    }
    setPersonModal({ ...personModal, visible: true });
  };

  function handSubmit(fieldsValue: any) {
    const res = transformDTO(fieldsValue);
    let pa = { ...res, force: true };
    onOk(pa);
    console.log("考评组", pa);
    onCancel && onCancel();
  }

  return (
    <Modal
      title={`${evaItem.name ? "编辑" : "新增"}考评组`}
      visible={visible}
      maskClosable={false}
      afterClose={() => {
        form.resetFields();
        onCancel();
      }}
      onCancel={() => onCancel()}
      onOk={form.submit}
      width={1400}
    >
      <Form form={form} labelCol={{ span: 6 }} wrapperCol={{ span: 16 }} onFinish={handSubmit}>
        <Form.Item name="name" label="考评组名称" rules={[{ required: true, message: "请输入名称" }]}>
          <Input placeholder="请输入考评组名称" disabled={readOnly} />
        </Form.Item>
        <Form.Item label="考评时间" name="time" rules={[{ required: true, message: "请选择考评时间" }]}>
          <RangePicker
            style={{ width: 900 }}
            disabled={readOnly}
            disabledDate={(current) => current && current < moment().add(-1, "days").endOf("day")}
          />
        </Form.Item>
        <Form.Item label="考评范围" name="scopeType" rules={[{ required: true, message: "请选择考评范围" }]}>
          <Radio.Group disabled={readOnly} onChange={(e) => setScopeType(e.target.value)}>
            <Radio value={1}>人员考评</Radio>
            <Radio value={2}>门店考评</Radio>
          </Radio.Group>
        </Form.Item>
        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) => prevValues.scopeType !== currentValues.scopeType}
        >
          {({ getFieldValue }) =>
            getFieldValue("scopeType") === 1 ? (
              <Form.Item name="post" label="岗位" rules={[{ required: true, message: "请选择岗位" }]}>
                <Select
                  labelInValue
                  placeholder="请选择岗位"
                  allowClear
                  disabled={readOnly}
                  showSearch
                  optionFilterProp="children"
                  onChange={(post: { label: string; value: number; key: number }) => {
                    setPersonModal({
                      postId: post.value,
                      visible: false,
                      shopIds: "",
                    });
                    setPostId(post.value);
                    form.setFieldsValue({ shop: [] });
                    // 根据岗位查门店
                    if (post) {
                      getDealerList(post.value);
                    }
                  }}
                >
                  {postList.map((item) => (
                    <Option value={item.id}>{item.postName}</Option>
                  ))}
                </Select>
              </Form.Item>
            ) : null
          }
        </Form.Item>

        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) => prevValues.scopeType !== currentValues.scopeType}
        >
          {({ getFieldValue }) => {
            const scopeType = getFieldValue("scopeType");
            return (
              <Form.Item name="shop" label="门店" rules={[{ required: true, message: "请选择门店" }]}>
                <ShopSelectNew
                  multiple
                  disabled={readOnly}
                  shopIds={scopeType === 1 ? shopList.map((item) => item.shopId) : []}
                  type={scopeType === 1 ? 2 : 1}
                  onChange={(
                    shops: {
                      key: number;
                      label: string;
                      value: number;
                    }[]
                  ) => {
                    const shopIds = shops.map((item) => item.value).join(",");
                    setPersonModal({ ...personModal, shopIds });
                  }}
                />
              </Form.Item>
            );
          }}
        </Form.Item>
        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) => prevValues.scopeType !== currentValues.scopeType}
        >
          {({ getFieldValue }) =>
            getFieldValue("scopeType") === 1 ? (
              <div style={{ marginBottom: 20, marginLeft: 250 }}>
                <a onClick={() => personView()}>{`人员查看 >`}</a>
              </div>
            ) : null
          }
        </Form.Item>
        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) => prevValues.scopeType !== currentValues.scopeType}
        >
          {({ getFieldValue }) =>
            getFieldValue("scopeType") === 2 ? (
              <Form.Item name="role" label="门店奖惩分配" rules={[{ required: true, message: "请选择管理角色" }]}>
                <Select
                  labelInValue
                  placeholder="请选择管理角色"
                  allowClear
                  disabled={readOnly}
                  showSearch
                  optionFilterProp="children"
                >
                  {roleList.map((item) => (
                    <Option value={item.roleCode}>{item.roleName}</Option>
                  ))}
                </Select>
              </Form.Item>
            ) : null
          }
        </Form.Item>

        <Form.Item noStyle shouldUpdate={(prevValues, currentValues) => prevValues.rewards !== currentValues.rewards}>
          {({ getFieldValue }) => {
            const rewards = getFieldValue("rewards");
            return (
              <Form.Item name="indicators" label="考评指标" rules={[{ required: !(rewards && rewards.length > 0) }]}>
                <IndivatorsTable postId={postId} personModal={personModal} scopeType={scopeType} />
              </Form.Item>
            );
          }}
        </Form.Item>
        <Form.Item
          noStyle
          shouldUpdate={(prevValues, currentValues) => prevValues.indicators !== currentValues.indicators}
        >
          {({ getFieldValue }) => {
            const indicators = getFieldValue("indicators");
            return (
              <Form.Item name="rewards" label="考评奖惩" rules={[{ required: !(indicators && indicators.length > 0) }]}>
                <RewardsTableSal postId={postId} personModal={personModal} scopeType={scopeType} />
              </Form.Item>
            );
          }}
        </Form.Item>
      </Form>

      <PersonModal item={personModal} setPersonModal={setPersonModal} />
    </Modal>
  );
}
