import { Block, Page, Panel, Toolbar } from '@bizComponents';
import { DataTable, EditableDataTable, Loader, UdcSelect, UploadEL, SuggestSelect } from '@components';
import { Button, Checkbox, Tooltip, Input, InputNumber, DatePicker, } from 'antd';
import { connect } from 'dva';
import Modal from './Modal';
import React from 'react';
import localCfg from './localCfg';
import { numberUtils } from '@utils';

const Detail = ({ accountBillList, accountDetails, dispatch, loading }) => {
  const { mode, total, list, listSummary, formData, viewSummary, summaryList, remoteCfg, modalVisible, modalItem, } = accountBillList;
  const { detailList, showDiff,showAccount, detailTotal, isAllAccount } = accountDetails;
  const { TextArea } = Input;
  const domain = 'accountBillList';
  const detailDomain = 'accountDetails';
  const { RangePicker } = DatePicker;

  // 返回
  const handleCancel = () => {
    dispatch({ type: `${domain}/cancel` });
  };

  // 保存
  const handleSave = () => {
    dispatch({ type: `${detailDomain}/save` });
  };

  // 提交
  const handleSubmit = () => {
    dispatch({ type: `${domain}/submit` });
  };

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

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

  // 审批意见
  const handleAdviceChange = (value) => {
    dispatch({ type: `${domain}/updateState`, payload: { advice: value } });
  };

  // 行编辑
  const handleChange = (key, index, newValue) => {
    dispatch({ type: `${detailDomain}/updateCell`, payload: { key, index, value: newValue } });
    // if(key==='diffQty'){
    //   dispatch({ type: `${detailDomain}/updateCell`, payload: { key:'diffPrice', index, value: null } });
    //   dispatch({ type: `${detailDomain}/updateCell`, payload: { key:'differenceAmt', index, value: null } });
    // }
    // if(key==='diffPrice'){
    //   dispatch({ type: `${detailDomain}/updateCell`, payload: { key:'diffQty', index, value: null } });
    //   dispatch({ type: `${detailDomain}/updateCell`, payload: { key:'differenceAmt', index, value: null } });
    // }
    // if(key==='differenceAmt'){
    //   dispatch({ type: `${detailDomain}/updateCell`, payload: { key:'diffQty', index, value: null } });
    //   dispatch({ type: `${detailDomain}/updateCell`, payload: { key:'diffPrice', index, value: null } });
    // }
  };

  const handleFormChange = (field) => {
    const key = Object.keys(field)[0];
    dispatch({
      type: `${domain}/updateForm`,
      payload: {
        key,
        value: field[key],
      },
    });
  };

  //弹窗
  const modalProps = {
    dispatch,
    loading,
    mode,
    domain,
    record: modalItem,
    visible: modalVisible,
    maskClosable: false,
    width: '80%',
    confirmLoading: mode === 'create' ? loading.effects[`${domain}/create`] : loading.effects[`${domain}/update`],
    readOnly: mode === 'view',
    title: '查看差异单',
    wrapClassName: 'vertical-center-modal',
    onOk(data) {
      dispatch({
        type: `${domain}/${mode}`,
        payload: data,
      });
    },
    onCancel() {
      dispatch({
        type: `${domain}/hideModal`,
      });
    },
  };

  // 单据列表
  const billProps = {
    rowKey: 'id',
    scroll: {
      x: '100%',
      y: 400,
    },
    sortDirection: 'DESC',
    domain,
    dispatch,
    loading,
    showAdd: false,
    showDelete: false,
    showEdit: false,
    showView: false,
    showColumn: false,
    total,
    filterMultiple: true,
    rowSelection: {
      type: 'checkbox',
    },
    dataSource: list,
    filter: [{
      title: '入库单编号',
      dataIndex: 'sourceDocNo',
      options: {
      },
      tag: <Input />,
    }, {
      title: '采购单编号',
      dataIndex: 'poNumber',
      options: {
      },
      tag: <Input />,
    }, {
      title: '业务类型',
      dataIndex: 'docType',
      options: {
      },
      tag: <UdcSelect domain="SRM" code="BILL_TYPE" />,
    }, {
      title: '入库日期',
      dataIndex: 'docDate',
      tag: (<RangePicker style={{ width: '100%' }} />),
    }, {
      title: '采购承诺交期',
      dataIndex: 'promiseDate',
      tag: (<RangePicker style={{ width: '100%' }} />),
    }, {
      title: '收货门店',
      dataIndex: 'outerShans',
      tag: <SuggestSelect apiName="outShans" mode="multiple" optionKey="code" params={{ ouId: formData.ouId }} disabled={formData.accountType==='1'?true:false}/>,
    },],
    columns: [{
      title: '入库单号',
      dataIndex: 'docNo',
      width: '15%',
    }, {
      title: '采购单号',
      dataIndex: 'poNumber',
      width: '15%',
    }, {
      title: '业务类型',
      dataIndex: 'docType',
      width: '10%',
    }, {
      title: '企业名称',
      className: 'alignLeft',
      dataIndex: 'ouName',
      width: '20%',
    }, {
      title: '入库日期',
      dataIndex: 'docDate',
      width: '10%',
    }, {
      title: '含税总额',
      dataIndex: 'amt',
      width: '10%',
      className: 'alignRight',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,2)
        );
      }
    }, {
      title: '未税总额',
      dataIndex: 'netAmt',
      width: '10%',
      className: 'alignRight',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,2)
        );
      }
    }, {
      title: '税额',
      dataIndex: 'taxAmt',
      width: '10%',
      className: 'alignRight',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,2)
        );
      }
    }],
    buttons: [{
      key: 'confirm',
      type: 'primary',
      name: '查看明细',
      requiredSelected: 0,
      cb: (selectedRowKeys) => {
        dispatch({ type: `${detailDomain}/queryDetail`, payload: { accountIds: selectedRowKeys } });
      },
    }],
  };
  // 汇总明细
  const sumProps = {
    rowKey: 'itemCode',
    scroll: {
      x: '100%',
      y: 400,
    },
    loading,
    dispatch,
    showAdd: false,
    showDelete: false,
    showCopy: false,
    showEdit: false,
    showView: false,
    enableSelection: true,
    rowSelection: {
      type: 'radio',
    },
    dataSource: summaryList,
    size: 'small',
    columns: [
      //   {
      //   title: '业务类型',
      //   dataIndex: 'docType',
      //   className: 'alignLeft',
      //   width: '10%',
      // },
      {
        title: '物料',
        dataIndex: 'item',
        width: '20%',
      }, {
        title: '数量',
        dataIndex: 'qty',
        width: '10%',
      }, {
        title: '含税单价',
        dataIndex: 'price',
        width: '10%',
        className: 'alignRight',
        render: (value, row, index) => {
          return (
            numberUtils.round_half_up_format(value,4)
          );
        }
      }, {
        title: '未税单价',
        dataIndex: 'netPrice',
        width: '10%',
        className: 'alignRight',
        render: (value, row, index) => {
          return (
            numberUtils.round_half_up_format(value,4)
          );
        }
      }, {
        title: '含税总额',
        dataIndex: 'amt',
        width: '10%',
        className: 'alignRight',
        render: (value, row, index) => {
          return (
            numberUtils.round_half_up_format(value,2)
          );
        }
      }, {
        title: '未税总额',
        dataIndex: 'netAmt',
        width: '10%',
        className: 'alignRight',
        render: (value, row, index) => {
          return (
            numberUtils.round_half_up_format(value,2)
          );
        }
      }, {
        title: '税率',
        dataIndex: 'taxRate',
        width: '10%',
        className: 'alignRight',
        render: (value, row, index) => {
          return (
            numberUtils.round_half_up_format(value,2)
          );
        }
      }, {
        title: '税额',
        dataIndex: 'taxAmt',
        width: '10%',
        className: 'alignRight',
        render: (value, row, index) => {
          return (
            numberUtils.round_half_up_format(value,2)
          );
        }
      }],
    buttons: [{
      key: 'itemDetails',
      type: 'primary',
      name: '查看物料明细',
      requiredSelected: 1,
      cb: (selectedRowKeys) => {
        dispatch({ type: `${detailDomain}/showSummaryDetails`, payload: { itemCode: selectedRowKeys[0] } });
      },
    }],
  };

  // 新增编辑时对账明细
  const detailProps = {
    rowKey: 'id',
    scroll: {
      x: 2300,
      y: 400,
    },
    enableSelection: false,
    //  enablePagination: false,
    sortDirection: 'DESC',
    domain: detailDomain,
    dispatch,
    loading,
    total: detailTotal,
    showAdd: false,
    showDelete: false,
    showEdit: false,
    showView: false,
    showColumn: false,
    handleTableChangeSave: true,
    dataSource: detailList,
    columns: [
      //   {
      //   title: '编辑',
      //   dataIndex: 'edit',
      //   width: 50,
      //   fixed: 'left',
      //   render: (value, row, index) => {
      //     return (
      //       <Icon type={row.editable ? 'check' : 'edit'} style={row.editable ? { color: 'green', fontSize: '22px' } : { color: '#3C91C2', fontSize: '22px' }}
      //         onClick={(e) => { if (row.editable) { dispatch({ type: `${detailDomain}/save`, payload: { index, row } }); } }}
      //       />);
      //   },
      // },
      {
        title: '要对账',
        dataIndex: 'accOver',
        width: 80,
        render: (value, row, index) => {
          return (
            <Checkbox checked={value === 1} disabled={true}/>);
        }
      },
      {
        title: '入库单号',
        dataIndex: 'docNo',
        width: 200,
      },
      {
        title: '物料',
        dataIndex: 'item',
        width: 200,
      },
      {
        title: '数量',
        dataIndex: 'qty',
        width: 120,
        className: 'alignRight',
        render: (value, row, index) => {
          return (
            numberUtils.round_half_up_format(value,2)
          );
        }
      }, {
        title: '含税单价',
        dataIndex: 'price',
        width: 120,
        className: 'alignRight',
        render: (value, row, index) => {
          return (
            numberUtils.round_half_up_format(value,4)
          );
        }
      }, {
        title: '含税总额',
        dataIndex: 'amt',
        width: 120,
        className: 'alignRight',
        render: (value, row, index) => {
          return (
            numberUtils.round_half_up_format(value,2)
          );
        }
      }, {
        title: '未税总额',
        dataIndex: 'netAmt',
        width: 120,
        className: 'alignRight',
        render: (value, row, index) => {
          return (
            numberUtils.round_half_up_format(value,2)
          );
        }
      },
      // {
      //   title: '单位',
      //   dataIndex: 'uom',
      //   width: 50,
      // },
      // {
      //   title: '规格',
      //   dataIndex: 'spec',
      //   width: 80,
      //   className: 'alignLeft',
      // },
      // {
      //   title: '税率(%)',
      //   dataIndex: 'taxRate',
      //   width: '5%',
      // },
      {
        title: '税额',
        dataIndex: 'taxAmt',
        width: 120,
        className: 'alignRight',
        render: (value, row, index) => {
          return (
            numberUtils.round_half_up_format(value,2)
          );
        }
      },
      // {
      //   title: '业务类型',
      //   dataIndex: 'docType',
      //   className: 'alignLeft',
      //   width: '8%',
      // },
      // {
      //   title: '未税单价',
      //   dataIndex: 'netPrice',
      //   width: 100,
      //   className: 'alignRight',
      //   render: (value, row, index) => {
      //     return (
      //       formatAmt(value,4)
      //     );
      //   }
      // },{
      //   title: '未税总额',
      //   dataIndex: 'netAmt',
      //   width: 100,
      //   className: 'alignRight',
      //   render: (value, row, index) => {
      //     return (
      //       formatAmt(value,2)
      //     );
      //   }
      // },
      {
        title: '无差',
        dataIndex: 'diffType',
        width: 80,
        render: (value, row, index) => {
          return (
            <Checkbox disabled={true} checked={value === "0"}
              // onChange={(e) => {
              //   dispatch({ type: `${detailDomain}/isAccount`, payload: { index, value: e.target.checked, row } });
              // }}
            />);
        }
      },

      {
        title: '实际数量',
        dataIndex: 'deliQty',
        width: 120,
        render: (value, row, index) => {
          return (
            <InputNumber value={value}
              formatter={(value) => {
                var parts = value.toString().split(".");
                parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                return parts.join(".");
              }}
              parser={(value) => value.replace(/(,*)/g, '')} maxLength={19}
              disabled={row.rowEditable !== 'D'} size="small"
              onChange={(value) => { handleChange('deliQty', index, value); }}
            />);
        },
      }, {
        title: '实际单价',
        dataIndex: 'deliPrice',
        width: 120,
        render: (value, row, index) => {
          return (
            <InputNumber value={value} precision={4} step={0.0001}
              formatter={(value) => {
                var parts = value.toString().split(".");
                parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
                return parts.join(".");
              }}
              parser={(value) => value.replace(/(,*)/g, '')} maxLength={19} size="small"
              disabled={row.rowEditable !== 'D'} onChange={(value) => { handleChange('deliPrice', index, value); }}
            />);
        },
      },
      {
        title: '实际总价',
        dataIndex: 'deliAmt',
        width: 120,
        className: 'alignRight',
        render: (value, row, index) => {
          return (
            numberUtils.round_half_up_format(value,2)
          );
        },
      },
      {
        title: '差异数量',
        dataIndex: 'diffQty',
        width: 120,
        className: 'alignRight',
        render: (value, row, index) => {
          return (
            numberUtils.round_half_up_format(value,2)
          );
        },
      }, {
        title: '差异单价',
        dataIndex: 'diffPrice',
        width: 120,
        className: 'alignRight',
        render: (value, row, index) => {
          return (
            numberUtils.round_half_up_format(value,4)
          );
        },
      },
      {
        title: '差异总价',
        dataIndex: 'differenceAmt',
        width: 120,
        className: 'alignRight',
        render: (value, row, index) => {
          return (
            numberUtils.round_half_up_format(value,2)
          );
        },

      },
      {
        title: '收货门店',
        dataIndex: 'outerShan',
        width: 200,
      },
      {
        title: '备注',
        dataIndex: 'diffRemark',
        render: (value, row, index) => {
          return (
            <TextArea rows={1} value={value} maxLength={500} size="small"
              onChange={(e) => { handleChange('diffRemark', index, e.target.value); }}
            />);
        },
      },
      // {
      //   title: '明细上传',
      //   dataIndex: 'file',
      //   width: '12%',
      //   render: (value, row, index) => {
      //     return (
      //       <UploadEL size={'small'} api={'/account/sfs-client/sfs/token'} dataKey={row.id}
      //         listType={'text'} disabled={row.rowEditable !== 'D'}
      //       />);
      //   },
      // },
    ],
  };

  // 查看模式时对账明细
  const accountProps = {
    rowKey: 'id',
    scroll: {
      x: 2300,
      y: 400,
    },
    enableSelection: false,
    //  enablePagination: false,
    sortDirection: 'DESC',
    domain: detailDomain,
    dispatch,
    loading,
    total: detailTotal,
    showAdd: false,
    showDelete: false,
    showEdit: false,
    showView: false,
    showColumn: false,
    dataSource: detailList,
    columns: [{
      title: '入库单号',
      dataIndex: 'docNo',
      width: 200,
    }, {
      title: '物料',
      dataIndex: 'item',
      width: 200,
      render: (value, row, index) => {
        if (value) {
          return value.length > 15 ? <Tooltip placement="bottom" title={value}>
            {value && `${value.slice(0, 15)}...`}
          </Tooltip> : value;
        } else {
          return '无';
        }
      },
    }, {
      title: '数量',
      dataIndex: 'qty',
      width: 120,
      className: 'alignRight',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,2)
        );
      }
    }, {
      title: '含税单价',
      dataIndex: 'price',
      width: 120,
      className: 'alignRight',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,4)
        );
      }
    }, {
      title: '含税总额',
      dataIndex: 'amt',
      width: 120,
      className: 'alignRight',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,2)
        );
      }
    }, {
      title: '未税总额',
      dataIndex: 'netAmt',
      width: 120,
      className: 'alignRight',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,2)
        );
      }
    },
    //  {
    //   title: '税率(%)',
    //   dataIndex: 'taxRate',
    //   width: '5%',
    // },
    {
      title: '税额',
      dataIndex: 'taxAmt',
      width: 120,
      className: 'alignRight',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,2)
        );
      }
    },
    // {
    //   title: '差异类型',
    //   dataIndex: 'diffType',
    //   fixed: 'right',
    //   width: 100,
    //   render: (value, row, index) => {
    //     return (
    //       <Select value={value} style={{ width: 80 }} disabled={true} size="small" onChange={(value) => {
    //         dispatch({ type: `${detailDomain}/editable`, payload: { index, value, row } });
    //       }}>
    //         <Option value="0">无差异</Option>
    //         <Option value="1">数量差异</Option>
    //         <Option value="2">价格差异</Option>
    //       </Select>);
    //   }
    // },

    {
      title: '无差',
      dataIndex: 'diffType',
      width: 80,
      render: (value, row, index) => {
        return (
          <Checkbox defaultChecked={value === "0" ? true : false} disabled={true}
            onChange={(e) => {
              dispatch({ type: `${detailDomain}/isAccount`, payload: { index, value: e.target.checked, row } });
            }}
          />);
      }
    },
    {
      title: '实际数量',
      dataIndex: 'deliQty',
      width: 120,
      className: 'alignRight',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,2)
        );
      }
    }, {
      title: '实际单价',
      dataIndex: 'deliPrice',
      width: 120,
        className: 'alignRight',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,4)
        );
      }
    },
    {
      title: '实际总价',
      dataIndex: 'deliAmt',
      width: 120,
      className: 'alignRight',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,2)
        );
      },
    },
    {
      title: '差异数量',
      dataIndex: 'diffQty',
      width: 120,
      className: 'alignRight',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,2)
        );
      },
    }, {
      title: '差异单价',
      dataIndex: 'diffPrice',
      width: 120,
        className: 'alignRight',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,4)
        );
      },
    },
    {
      title: '差异总价',
      dataIndex: 'differenceAmt',
      width: 120,
      className: 'alignRight',
      render: (value, row, index) => {
        return (
          numberUtils.round_half_up_format(value,2)
        );
      },
    },
    {
      title: '收货门店',
      dataIndex: 'outerShan',
      width: 200,
    },
    {
      title: '备注',
      dataIndex: 'diffRemark',
      render: (value, row, index) => {
        if (value) {
          return value.length > 15 ? <Tooltip placement="bottom" title={value}>
            {value && `${value.slice(0, 15)}...`}
          </Tooltip> : value;
        } else {
          return '无';
        }
      },
    },
      // {
      //   title: '明细上传',
      //   dataIndex: 'file',
      //   fixed: 'right',
      //   width: 100,
      //   render: (value, row, index) => {
      //     return (
      //       <UploadEL size={'small'} api={'/account/sfs-client/sfs/token'} dataKey={row.sourceId}
      //         listType={'text'} disabled={true}
      //       />);
      //   },
      // }

    ],
  };

  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 === 'advice')['onChange'] = (e) => handleAdviceChange(e.target.value);
    remoteCfg.buttons.find((b) => b.id === 'approve')['onClick'] = () => handleApprove()
    remoteCfg.buttons.find((b) => b.id === 'reject')['onClick'] = () => handleReject()

    const buttons = [{
      id: 'showRecps',
      text: '查看差异单',
      type: 'primary',
      hidden: formData.diffFlag !== '1' || formData.status === '01' || formData.status === '02',
      onClick: () => {
        dispatch({
          type: `${domain}/modal`,
        });
      },
    },
    ...remoteCfg.buttons,
    ];

    return (

      <div>
        <Toolbar prcId={formData.prcId} defId={formData.defId} loading={loading} record={formData} mode={mode}
          buttons={buttons}
          handleCancel={handleCancel}
        />
        <Page dispatch={dispatch} loading={loading} localCfg={localCfg} remoteCfg={remoteCfg} id="accountCheck">

          <Panel id="basic" title="基本信息">
            <Block id="basic" type="form" data={formData} onFieldsChange={handleFormChange} />
          </Panel>

          <Panel id="billProps" title="单据列表">
            <Block id="basic" type="other">
              <DataTable {...billProps} />
            </Block>
          </Panel>

          <Panel id="billSum" title="单据汇总">
            <Block id="billSums" type="form" data={listSummary} />
          </Panel>

          <Panel id="detailProps" title={<div>对账明细  {/*<Button key="save" type="primary" onClick={() => {
            dispatch({ type: `${detailDomain}/save` });
          }} disabled={loading.effects[`${detailDomain}/save`]} >确认</Button>*/}
            <Button key="allAccTrue" type="primary" style={{ marginLeft: '7px' }} onClick={() => {
              dispatch({ type: `${detailDomain}/isAllAccount`, payload: { isAllAccount: true } });
            }}>全部对账</Button>
            <Button key="allAccFalse" type="primary" style={{ marginLeft: '7px' }} onClick={() => {
              dispatch({ type: `${detailDomain}/isAllAccount`, payload: { isAllAccount: false } });
            }}>全不对账</Button>
            <Button key="showDiff" type="primary" style={{ marginLeft: '7px' }} onClick={() => {
              dispatch({ type: `${detailDomain}/showDiff`, payload: {} });
            }}> {showDiff ? "查看全部" : "查看差异"}</Button>
            <Button key="showAccount" type="primary" style={{ marginLeft: '7px' }} onClick={() => {
              dispatch({ type: `${detailDomain}/showAccount`, payload: { id: formData.id } });
            }}> {showAccount ? "查看全部" : "查看未对帐"}</Button>
          </div>}>
            <Block id="basic" type="other">
              {Object.keys(formData).length > 0 && <DataTable {...detailProps} />}
            </Block>
          </Panel>

          <Panel id="accountProps" title={<div>对账明细
            <Button key="showDiff" type="primary" style={{ marginLeft: '7px' }} onClick={() => {
              dispatch({ type: `${detailDomain}/showDiff`, payload: { id: formData.id } });
            }}> {showDiff ? "查看全部" : "查看差异"}</Button>
            {/* <Button key="showAccount" type="primary" style={{ marginLeft: '7px' }} onClick={() => {
              dispatch({ type: `${detailDomain}/showAccount`, payload: { id: formData.id } });
            }}> {showAccount ? "查看全部" : "查看未对帐"}</Button> */}
          </div>}>
            <Block id="basic" type="other">
              {Object.keys(formData).length > 0 && <DataTable {...accountProps} />}

            </Block>
          </Panel>

          <Panel id="sumProps" title={<div>物料汇总
              <Button key="save" type="primary" onClick={() => {
                dispatch({ type: `${domain}/viewSummary` });
              }}>查看物料汇总</Button>
            </div>}>
            <Block id="basic" type="other">
              <EditableDataTable {...sumProps} />
            </Block>
          </Panel>
        </Page>
        {modalVisible && <Modal {...modalProps} />}
      </div>
    );
  } else {
    return <Loader fullScreen={false} spinning={mode === 'create' ? loading.effects[`${domain}/newCreate`] : loading.effects[`${domain}/initWithForm`]} />;
  }
};

export default connect(({ accountBillList, accountDetails, loading }) => ({
  accountBillList,
  accountDetails,
  loading,
}))(Detail);
