import React from 'react';
import { connect } from 'dva';
import compareDetailCfg from './compareDetailCfg';
import { message, Card } from 'antd';
import { Block, Page, Panel, Toolbar } from '@bizComponents';
import { Loader, EditableDataTable, DataTable } from '@components';

const compareDetail = ({ user, compareDetail, dispatch, loading }) => {
  const { mode, list, substituteList, formData, remoteCfg, collectData } = compareDetail;
  const domain = 'compareDetail';
  let readOnly = true;

  if (mode === 'view' || mode === 'approval') {
    readOnly = true;
  } else if (mode === 'update' || mode === 'create') {
    readOnly = false;
  }

  const onSelect = (record, selected, selectedRows, selectedRowKeys) => {
    dispatch({
      type: `${domain}/substitutes`,
      payload: {
        itemId: selectedRows[0].itemId,
        itemCode: selectedRows[0].itemCode,
        itemName: selectedRows[0].itemName,
        toDate: formData.priceEffectDate
      }
    })
  }

  const tableProps = {
    rowKey: 'pqdDocId',
    scroll: {
      x: 3850,
      y: 500,
    },
    domain,
    dispatch,
    loading,
    dataSource: list,
    showAdd: false,
    showEdit: false,
    showView: false,
    showDelete: false,
    showCopy: false,
    size: 'small',
    readOnly,
    rowSelection: {
      columnWidth: 20,
      fixed: true,
      type: 'radio',
      onSelect: onSelect
    },
  };

  const substituteTableProps = {
    enableSelection: false,
    scroll: {
      x: 1350,
    },
    domain,
    dispatch,
    loading,
    dataSource: substituteList,
    showAdd: false,
    showDelete: false,
    showCopy: false,
    size: 'small',
    readOnly,
  };

  const compareTableProps = {
    enableSelection: false,
    scroll: { x: '100%' },
    domain,
    dispatch,
    loading,
    dataSource: collectData,
    showAdd: false,
    showDelete: false,
    showCopy: false,
    size: 'small',
    readOnly,
    columns: [
      {
        title: '供应商名称',
        dataIndex: 'suppName',
        width: '25%',
      },
      {
        title: '物料品项数',
        dataIndex: 'itemCount',
        width: '25%',
      },
      {
        title: '物料数量',
        dataIndex: 'itemNumber',
        width: '25%',
      },
      {
        title: '总金额',
        dataIndex: 'itemAmt',
        width: '25%',
      },
    ],
  }

  // 保存操作不进行物料分配比例校验
  const handleSave = () => {
      dispatch({
        type: `${domain}/update`,
        payload: {
          isSubmit: false
        }
      })
  };

  //判断物料分配比例总和是否为100%
  const handleSubmit = () => {
    let confirmFlag = true;
    let list = formData.srmCompItemsInfoList;
    let items = new Map();
    list.map((i) => {
      // 没有填写分配比例的默认为0
      i.percent = i.percent ? i.percent : 0;
      if (items.has(i.itemId)) {
        let { percent } = items.get(i.itemId);
        items.set(i.itemId, { name: i.itemName, percent: percent + i.percent });
      } else {
        items.set(i.itemId, { name: i.itemName, percent: i.percent });
      }
    });
    let keys = Array.from(items.keys());
    for (let key of keys) {
      if (items.get(key).percent !== 100) {
        message.warn("物料: " + items.get(key).name + " 的分配比例总和必须为 100%");
        confirmFlag = false;
        break;
      }
    }
    if (confirmFlag) {
      dispatch({
        type: `${domain}/update`,
        payload: {
          isSubmit: true
        }
      })
    }
  };

  const handleApprove = () => {
    dispatch({ type: `${domain}/approve` });
  };

  const handleReject = () => {
    dispatch({ type: `${domain}/reject` });
  };

  const handleAdviceChange = (newValue) => {
    dispatch({
      type: `${domain}/updateState`,
      payload: { advice: newValue },
    });
  };

  if (remoteCfg) {



    remoteCfg.buttons.find(b => b.id === 'save')['onClick'] = () => {
      handleSave();
    };

    remoteCfg.buttons.find(b => b.id === 'submit')['onClick'] = () => {
      handleSubmit();
    };

    remoteCfg.buttons.find(b => b.id === 'approve')['onClick'] = () => {
      handleApprove();
    };

    remoteCfg.buttons.find(b => b.id === 'reject')['onClick'] = () => {
      handleReject();
    };

    // remoteCfg.buttons.find(b => b.id === 'complete')['onClick'] = () => {
    //   handleApprove();
    // };

    const buttons = [
      {
        id: 'advice',
        placeholder: '审批意见',
        hidden: mode !== 'approval',
        onChange: (e) => {
          handleAdviceChange(e.target.value);
        },
      },
      ...remoteCfg.buttons,
    ];

    return (
      <div>
        <Toolbar prcId={formData.prcId} defId={formData.defId} loading={loading} record={formData} mode={mode} buttons={buttons}
          handleCancel={() => {
            dispatch({ type: `${domain}/cancel` });
          }}
        />

        <Page dispatch={dispatch} loading={loading} localCfg={compareDetailCfg} remoteCfg={remoteCfg} id="compareDetail">

          <Panel id="base" title="基本信息">
            <Block id="basicInfo" type="form" data={formData} />
          </Panel>

          <Card title="汇总列表" loading={loading.effects[`${domain}/queryDetails`]} id="collection">
            <EditableDataTable {...compareTableProps} />
          </Card>

          <Card id="compare" title="整体比价结果列表" loading={loading.effects[`${domain}/queryDetails`]}>
            <DataTable id="compareList"
                       columns={compareDetailCfg(formData, mode, dispatch, loading).compareList}
                       data={list}
                       {...tableProps} />
          </Card>

          <Panel id="substitute" title="替代物料参考列表">
            <Block id="substituteList" type="table" data={substituteList} {...substituteTableProps} />
          </Panel>
        </Page>
      </div>
    );
  } else {
    return <Loader fullScreen={false} spinning={loading.effects[`${domain}/query`]} />;
  }

};

export default connect(({ compareDetail, loading }) => ({ compareDetail, loading }))(compareDetail);
