import React, { useState, useEffect, useRef } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { Card, Table, Button, Row, DatePicker, Col, InputNumber, message } from 'antd';
import { getRetailManualList, ListItem, autoAlloctionApi, ShopTaskList, save, saveParams } from './api';
import EModal from './component/Modal';
import moment from 'moment';
import currency from 'currency.js';
import ApproveModal from '@/pages/order3/Common/ApproveModal';

const { Column } = Table;

const day = new Date();
const month = day.getMonth() + 1;
const year = day.getFullYear();
const strtime = year + '-' + month;
let newDate = new Date(strtime);
const newDay = newDate.getTime();

export default function TacklingCarModels() {
  const [visible, setVisible] = useState<boolean>(false);
  const [loading, setLoading] = useState<boolean>(false);
  const [current, setCurrent] = useState<ShopTaskList>({});
  const [confirmLoading, setConfirmLoading] = useState<boolean>(false);
  const [saveLoading, setSaveLoading] = useState<boolean>(false);
  const [date, setDate] = useState<number>(newDay);
  const [edit, setEdit] = useState<boolean>(false);
  const [list, setList] = useState<ListItem>({});
  const [orginDara, setOrginDara] = useState<ListItem>({});
  const index = useRef();
  const [approveOpen, setApproveOpen] = useState<boolean>(false);
  // let index;

  useEffect(() => {
    getList(newDay);
  }, []);

  function setReset() {
    setList({ ...orginDara });
    setEdit(false);
  }

  //查询列表
  function getList(date: number) {
    const params = {
      taskDate: date.valueOf(),
      autoAssign: true,
    };
    getRetailManualList(params).then(res => {
      setLoading(false);
      const data = res.data;
      setOrginDara(data || {});
      setList(data || {});
      // message.success(res.result);
    }).catch(e => {
      setLoading(false);
      message.warning(e.message);
    });
  }

  /**
   * 修改零售任务数量
   * @param e 
   * @param index 
   */
  function _onChange(e: number, index: number) {
    const data = JSON.parse(JSON.stringify(list));
    data.shopTaskList![index].taskCount = e;
    data.shopTaskList![index].clueDealTaskCount = currency(e || 0).multiply(data.shopTaskList[index].clueDealTaskRate || 0).divide(100).value;
    // data.shopTaskList![index].clueDealTaskCount = Math.ceil((e || 0)*((data.shopTaskList![index].clueDealTaskRate || 0)/100));
    setList({ ...data });
  }

    /**
   * 修改线索到店零售数量
   * @param e 
   * @param index 
   */
  function handleChangeClue(e: number, index: number) {
    const data = JSON.parse(JSON.stringify(list));
    if (data.shopTaskList[index].taskCount < e) {
      message.error("线索到店零售数量不能大于零售任务！");
      return;
    }
    data.shopTaskList![index].clueDealTaskCount = e;
    setList({ ...data });
  }

  function _ChangeMoth(date: any) {
    setLoading(true);
    setDate(date.valueOf());
    getList(date);
  }
  //保存
  function handleClick() {
    setLoading(true);
    const params = {
      id: list.id,
      shopTaskList: list.shopTaskList
    };
    autoAllocationSave(params);
  }

  function handleOpenApprove() {
    setApproveOpen(true);
  }

  //提交审批
  function saveClick(params?: any) {
    setLoading(true);
    setSaveLoading(true);
    save({...params, id: list.id}).then((res) => {
      setSaveLoading(false);
      setLoading(false);
      setList({ ...list, canModified: false });
      message.success(res.result);
    }).catch(e => {
      setLoading(false);
      message.warning(e.message);
      setSaveLoading(false);
    });
  }

  //自动提交
  function autoAllocationSave(params: saveParams) {
    setConfirmLoading(true);
    setEdit(true);
    autoAlloctionApi(params).then((res) => {
      setConfirmLoading(false);
      getList(date);
      setEdit(false);
      message.success(res.result);
    }).catch(e => {
      message.warning(`${e.message}`);
      setConfirmLoading(false);
      setLoading(false);
    });
  }

  return (
    <PageHeaderWrapper title="零售任务">
      <Card>
        <Row style={{ marginTop: 20, marginBottom: 20 }}>
          <Col span={4}><DatePicker defaultValue={moment(newDay)} picker="month" onChange={_ChangeMoth} /></Col>
        </Row>
        <Table
          dataSource={list.shopTaskList}
          loading={loading}
          rowKey="shopId"
          pagination={false}
          summary={pageData => {
            let total = 0;
            pageData.forEach(({ taskCount }) => {
              total += taskCount || 0;
            });
            return (
              <>
                {total == 0 ? null :
                  (
                    <Table.Summary.Row>
                      <Table.Summary.Cell index={1}><span style={{ display: 'block', textAlign: 'center' }}>合计</span></Table.Summary.Cell>
                      <Table.Summary.Cell index={2}>
                        <span style={{ display: 'block', textAlign: 'center' }}>{total}</span>
                      </Table.Summary.Cell>
                      <Table.Summary.Cell index={3} />
                    </Table.Summary.Row>
                  )}
              </>
            );
          }}
        >
          <Column title="门店" dataIndex="shopName" align="center" />
          <Column
            title="零售任务(台)"
            dataIndex="taskCount"
            align="center"
            render={(value, record, index) => {
              if (edit) {
                return <InputNumber min={0} value={value} onChange={(e: any) => _onChange(e, index)} />;
              } else {
                return <span>{value}</span>;
              }
            }}
          />
          <Column
            title="线索到店零售数量"
            dataIndex="clueDealTaskCount"
            align="center"
            render={(value, record, index) => <span>{value}</span>}
          />
          <Column
            title="操作"
            align="center"
            render={(value, record, _index) => (
              <>
                <Button type="link" onClick={() => { setVisible(true); setCurrent(value); index.current = _index; }}>销售顾问任务</Button>
              </>
            )}
          />
        </Table>
        <EModal setVisible={setVisible} visible={visible} current={current} index={index.current} setList={setList} list={list} setCurrent={setCurrent} isHandledit={edit} />
        <Row justify="center" style={{ marginTop: 15 }}>
          {list.canModified ?
            (
              <>
                {edit ?
                  <Button style={{ width: 110 }} type="primary" onClick={handleClick} loading={confirmLoading}>确定</Button> :
                  <Button style={{ width: 110 }} type="primary" onClick={handleOpenApprove} loading={saveLoading}>提交审批</Button>}
                {edit ? null :
                <Button style={{ width: 110, marginLeft: 15, backgroundColor: '#FFF' }} onClick={() => setEdit(true)} type="default">自动调整</Button>}
                {edit ?
                  <Button style={{ width: 110, marginLeft: 15 }} type="default" onClick={setReset} loading={confirmLoading}>取消</Button> :
                  null}
              </>
            )
            : null}
        </Row>
      </Card>
      <ApproveModal callback={saveClick} open={approveOpen} setOpen={setApproveOpen} />
    </PageHeaderWrapper>
  );
}