import {Card, ConfigProvider, Select, Button, message, Popconfirm} from 'antd';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import React, {useEffect, useState} from "react";
import DealerModal from './components/DealerModal';
import SuppModal from './components/SuppModal';
import PartDetailModal from './components/PartDetailModal';
import {throttle, sum} from 'lodash';
import useInitial from "@/hooks/useInitail";
import * as API from "@/common/api";
import {getList, Params, ListVO} from "@/pages/pms/partPlan/PlanPool/api";
import {saveApi, draftApi} from './api';
import zhCN from "antd/lib/locale-provider/zh_CN";
import st from "@/pages/pms/partPlan/PlanManage/style.less";
import PartModal from "@/pages/pms/partPlan/PlanManage/subpages/Apply/components/PartModal";
import {groupBys, flattenDeep} from '@/pages/pms/entity';
import {PartDetail} from '../../api';
import { history } from 'umi';
import { getDetail, DetailVO, Params as detailParams } from '../Detail/api';

const { Option } = Select;
const apiObj: { [key: number]: any } = {
  1: saveApi,
  2: draftApi
};
export default function Index() {
  const planId = history.location.query;
  const [detaildelay, setDetaildelay] = useState(true);
  const { data, setParams: detailsetParams } = useInitial<DetailVO[], detailParams>(getDetail, [], { ...planId }, detaildelay);
  const [delay, setDelay] = useState<boolean>(true);
  const [loading, setLoading] = useState<boolean>(false);
  const { data: brands } = useInitial(API.getBrandFilterApi, [], {});
  const [dfParams, setDfParams] = useState<any>({});
  const { data: parts, setParams } = useInitial<ListVO[], Params>(getList, [], dfParams, delay);
  const [dealerList, setDealerList] = useState<any[]>([]);
  const [dealer, setDealer] = useState<any>({});
  const [visibleDealer, setVisibleDealer] = useState(false);
  const [visibleSupplier, setVisibleSupplier] = useState(false);
  const [visiblePart, setVisiblePart] = useState(false);
  const [visiblePartDetail, setVisiblePartDetail] = useState(false);
  const partList = flattenDeep(dealerList.map(it => (it.suppliers || []).map((su: any) => (su.storages || []).map((st: any) => (st.parts || [])))));
  const poolIds = partList.map((it: any) => it.poolId);

  useEffect(() => {
    if (planId?.planId) {
      setDetaildelay(false);
      detailsetParams({ ...planId }, true);
    }
  }, []);
 
  useEffect(() => {
    if (data.length) {
      setDfParams({brandId: data[0].brandId});
      setParams({}, true);
      setDelay(false);
      setDealerList(data);
    }
  }, [data.length]);

  function onOk(parts: ListVO[] = []) {
    setDealerList(dealerList.map(it => {
      if (it.settleDealerId == dealer.settleDealerId) {
        return {
          ...it,
          suppliers: (it.suppliers || []).map((su: any) => {
            if (su.supplierId == dealer.supplierId) {
              const pas = [...flattenDeep((su.storages || []).map((st: any) => (st.parts || []))), ...parts];
              const sto = groupBys(pas, 'storageId', 'storageName');
              return {
                ...su,
                storages: sto.map(st => ({
                  storageId: st.storageId,
                  storageName: st.storageName,
                  parts: st.list,
                }))
              };
            }
            return su;
          })
        };
      }
      return it;
    }));
  }

  function onOkDealer(dealer: any = {}) {
    setDealerList([...dealerList, dealer]);
  }

  function onOkSupplier(supplier: any = {}) {
    setDealerList(dealerList.map(it => {
      if (it.settleDealerId == dealer.settleDealerId) {
        return {
          ...it,
          suppliers: [...(it.suppliers || []), supplier]
        };
      }
      return it;
    }));
  }

  function deleteSupplier(dealer: any = {}, supplier: any = {}) {
    setDealerList(dealerList.map(it => {
      if (it.settleDealerId == dealer.settleDealerId) {
        return {
          ...it,
          suppliers: (it.suppliers || []).filter((su: any) => su.supplierId != supplier.supplierId)
        };
      }
      return it;
    }));
  }

  function deletePart(dealer: any = {}, supplier: any = {}, storage: any = {}, part: any = {}) {
    setDealerList(dealerList.map(it => {
      if (it.settleDealerId == dealer.settleDealerId) {
        return {
          ...it,
          suppliers: (it.suppliers || []).map((su: any) => {
            if (su.supplierId == supplier.supplierId) {
              return {
                ...su,
                storages: (su.storages || []).map((st: any) => {
                  if (st.storageId==storage.storageId) {
                    return {
                      ...st,
                      parts: (st.parts || []).filter((p: any) => p.poolId!=part.poolId)
                    };
                  }
                  return st;
                })
              };
            }
            return su;
          })
        };
      }
      return it;
    }));
  }

  function deleteStorage(dealer: any = {}, supplier: any = {}, storage: any = {}) {
    setDealerList(dealerList.map(it => {
      if (it.settleDealerId == dealer.settleDealerId) {
        return {
          ...it,
          suppliers: (it.suppliers || []).map((su: any) => {
            if (su.supplierId == supplier.supplierId) {
              return {
                ...su,
                storages: (su.storages || []).filter((st: any) => st.storageId!=storage.storageId)
              };
            }
            return su;
          })
        };
      }
      return it;
    }));
  }

  const onSubmit = throttle((isSave) => {
    setLoading(true);
    let suppliers = flattenDeep(dealerList.map(de => (de.suppliers || []).map((su: any) => ({...de, ...su}))));
    suppliers = suppliers.map(su => ({
      ...su,
      settleDealerId: su.settleDealerId,
      storages: (su.storages || []).map((st: any) => ({
        storageId: st.storageId,
        poolIds: (st.parts || []).map((pa: any) => pa.poolId)
      }))
    }));
    const type = isSave ? 1 : 2;
    apiObj[type]({
      planId: planId?.planId,
      ...dfParams,
      suppliers
      // suppliers: suppliers.map(i => ({ 
      //   settleDealerId: i.settleDealerId,
      //   settleDealerName: i.settleDealerName,
      //   supplierId: i.supplierId,
      //   supplierName: i.supplierName,
      //   storages: i.storages
      // }))
    }).then(() => {
      setLoading(false);
      history.goBack();
    }).catch((e: any) => {
      setLoading(false);
      message.error(e.message);
    });
  }, 3000);

  return (
    <PageHeaderWrapper title="配件计划管理">
      <ConfigProvider locale={zhCN}>
        <Card className={st.page}>
          <div style={{ display: 'flex', flexDirection: 'column', marginTop: 20, marginBottom: 20 }}>
            <div style={{ display: 'flex', flexDirection: 'row', alignItems: 'center'}}>
              <Select
                placeholder="请选择品牌"
                onSearch={() => {}}
                showSearch
                filterOption={(input: any, option: any) => option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0}
                style={{ width: 200, marginBottom: 20 }}
                value={dfParams.brandId}
                onChange={brandId => {
                  setDfParams({ ...dfParams, brandId });
                  setParams({}, true);
                  setDelay(false);
                  setDealerList([]);
                }}
              >
                {brands.map((item: any) => (
                  <Option value={item.id} key={item.id}>
                    {item.name}
                  </Option>
                ))}
              </Select>
              <a
                style={{marginLeft: 20, marginBottom: 20}}
                onClick={() => {
                  if (!dfParams.brandId) {
                    message.error('请选择品牌');
                    return;
                  }
                  setVisibleDealer(true);
                }}
              >
                添加采购商家
              </a>
            </div>
            {dealerList.map((dealer: any = {}) => (
              <div key={`dealer${dealer.settleDealerId}`} style={{ marginTop: 10 }}>
                <div style={{ display: 'flex', flexDirection: 'row', alignItems: 'center'}}>
                  <div style={{ fontWeight: "bold" }}>{`商家: ${dealer.settleDealerName || ''}`}</div>
                  <a style={{marginLeft: 40}} onClick={() => { setVisibleSupplier(true); setDealer(dealer); }}>
                    添加指定供应商
                  </a>
                  <Popconfirm
                    title="是否删除"
                    onConfirm={() => setDealerList(dealerList.filter(it => it.settleDealerId!=dealer.settleDealerId))}
                    okText="确定"
                    cancelText="取消"
                    style={{marginLeft: 20}}
                  >
                    <Button type="link" danger>
                      删除
                    </Button>
                  </Popconfirm>
                </div>
                {(dealer.suppliers || []).map((supplier: any = {}) => {
                  const paList: any[] = flattenDeep((supplier.storages || []).map((st: any) => (st.parts || [])));
                  return (
                    <div key={`supplier${supplier.supplierId}`} style={{ marginTop: 10, marginLeft: 40 }}>
                      <div style={{ display: 'flex', flexDirection: 'row', alignItems: 'center'}}>
                        <div style={{ fontWeight: "bold" }}>{`供应商: ${supplier.supplierName || ''}`}</div>
                        <a style={{marginLeft: 20}} onClick={() => { setVisiblePart(true); setDealer({...dealer, ...supplier}); }}>
                          添加采购配件
                        </a>
                        <Popconfirm
                          title="是否删除"
                          onConfirm={() => deleteSupplier(dealer, supplier)}
                          okText="确定"
                          cancelText="取消"
                          style={{marginLeft: 20}}
                        >
                          <Button type="link" danger>
                            删除
                          </Button>
                        </Popconfirm>
                      </div>
                      <div style={{display: 'flex', marginLeft: 40, marginTop: 10}}>
                        <div style={{marginRight: 20}}>
                          {`总金额: ${sum(paList.map((it: any) => (it.price || 0) * (it.count || it.partCnt || 0))).toFixed(2)}元`}
                        </div>
                        <div>{`品种数: ${[...new Set((paList || []).map((i: PartDetail) => i.partCode))].length}种`}</div>
                      </div>
                      {(supplier.storages || []).map((storage: any) => (
                        <div key={`storage${storage.storageId}`} style={{ marginTop: 10, marginLeft: 60 }}>
                          <div style={{ display: 'flex', flexDirection: 'row', alignItems: 'center'}}>
                            <div style={{ fontWeight: "bold" }}>{`发运库房: ${storage.storageName || ''}`}</div>
                            <div style={{marginLeft: 20}}>{`总金额: ${sum((storage.parts || []).map((it: any) => (it.price || 0) * (it.count || it.partCnt || 0))).toFixed(2)}元`}</div>
                            <div style={{marginLeft: 20}}>{`品种数: ${[...new Set((storage.parts || []).map((i: PartDetail) => i.partCode))].length}种`}</div>
                            <a style={{marginLeft: 20}} onClick={() => { setVisiblePartDetail(true); setDealer({dealer, supplier, storage }); }}>
                              查看配件
                            </a>
                            <Popconfirm
                              title="是否删除"
                              onConfirm={() => deleteStorage(dealer, supplier, storage)}
                              okText="确定"
                              cancelText="取消"
                              style={{marginLeft: 20}}
                            >
                              <Button type="link" danger>
                                删除
                              </Button>
                            </Popconfirm>
                          </div>
                        </div>
                      ))}
                    </div>
                  );
                })}
              </div>
            ))}
            <DealerModal
              dealerList={dealerList}
              visible={visibleDealer}
              onCancel={() => setVisibleDealer(false)}
              onOk={onOkDealer}
            />
            <SuppModal
              brandId={dfParams.brandId}
              supplierList={dealer.suppliers || []}
              visible={visibleSupplier}
              onCancel={() => setVisibleSupplier(false)}
              onOk={onOkSupplier}
            />
            <PartModal
              visible={visiblePart}
              onCancel={() => setVisiblePart(false)}
              parts={parts.filter(it => !poolIds.includes(it.poolId))}
              onOk={onOk}
              setParams={setParams}
            />
            <PartDetailModal
              visible={visiblePartDetail}
              onCancel={() => setVisiblePartDetail(false)}
              dealer={dealer.dealer}
              supplier={dealer.supplier}
              storage={dealer.storage}
              deletePart={deletePart}
            />
          </div>
          <div style={{display: 'flex', justifyContent: 'center'}}>
            <Popconfirm
              title="确定取消"
              onConfirm={() => history.goBack()}
              okText="确定"
              cancelText="取消"
            >
              <Button
                disabled={loading}
                loading={loading}
                style={{marginRight: 20}}
              >
                取消
              </Button>
            </Popconfirm>
            <Button
              disabled={loading}
              loading={loading}
              onClick={() => onSubmit(false)}
              type="primary"
              style={{marginRight: 20}}
            >
              暂存为草稿
            </Button>
            <Button
              disabled={loading}
              loading={loading}
              onClick={() => onSubmit(true)}
              type="primary"
            >
              确认并提交
            </Button>
          </div>
          
        </Card>
      </ConfigProvider>
    </PageHeaderWrapper>
  );
}
