import {Card, Input, InputNumber, message, Button, List} from 'antd';
import Schema from 'async-validator';
import {connect} from 'dva';
import {routerRedux} from 'dva/router';
import React from 'react';
import {EditableDataTable, FormEL, UploadEL} from '../../../components';
import {dataUtils, formUtils} from '../../../utils';
import {Toolbar} from '../../components';
import { update } from '../../../services/source/bids';

const Detail = ({quoteDetails, dispatch, loading}) => {

  const {mode, list, substituteList, currentItem, formData, confirmBtnFlag} = quoteDetails;
  // console.log("list==>",list)
  const domain = 'quoteDetails';
  const domainCN = '整体比价结果';
  const readOnly = false;

  const handleChange = (key, index, newValue) => {
    dispatch({type: `${domain}/updateCell`, payload: {key, index, value: newValue}});
  };

  const handleFormChange = (field) => {
    const key = Object.keys(field)[0];

    if (key === 'productCode') {
      // console.log('21333333333', field[key]);
      if (field[key] !== null) {
        dispatch({
          type: `${domain}/updateSpecNo`,
          payload: {
            productCode: field[key],
          },
        });
      } else {
        dispatch({
          type: `${domain}/updateForm`,
          payload: {
            key: 'specNo',
            value: null,
          },
        });
      }
    } else if (key === 'dutyType') {
      dispatch({type: `${domain}/updateOuId`, payload: {value: field[key]}});
    }

    dispatch({
      type: `${domain}/updateForm`,
      payload: {
        key,
        value: field[key],
      },
    });
  };

  //判断物料分配比例总和是否为100%
  const handleConfirm = (formData) => {
    let confirmFlag = true;
    let list = formData.srmCompItemsInfoList;
    let items = new Map();
    list.map((i) => {
      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`
      })
    }
  };

  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 handleCancel = () => {
    dispatch({type: `${domain}/cancel`, payload: {mode: 'view'}});
  };

  // 基本信息form
  const basic = [
    {
      title: '供货区域',
      dataIndex: 'suppArea',
    }, {
      title: '价格生效期间',
      dataIndex: 'priceInterval',
    }, {
      title: '报价截止时间',
      dataIndex: 'quoteDeadline',
    }, {
      title: '议价截止日时间',
      dataIndex: 'bargainDeadline',
    }];

  // 物料列
  const tableProps = {
    scroll: {
      x: 3500,
      columnWidth: 30,
    },
    domain,
    dispatch,
    loading,
    dataSource: list,
    showAdd: false,
    showDelete: false,
    showCopy: false,
    size: 'small',
    readOnly,
    rowSelection: {
      type: 'radio',
      onSelect: onSelect
    },
    columns: [{
      title: '供应商名称',
      dataIndex: 'suppName',
      width: 120,
      className: 'alignLeft',
    }, {
      title: '物料名称',
      dataIndex: 'itemName',
      width: 120,
      className: 'alignLeft',
    }, {
      title: '物料编号',
      dataIndex: 'itemCode',
      width: 100,
      className: 'alignLeft',
    }, {
      title: '物料规格',
      dataIndex: 'itemSpec',
      width: 80,
      className: 'alignLeft',
    }, {
      title: '单位',
      dataIndex: 'itemUomDesc',
      width: 80,
      className: 'alignLeft',
    }, {
      title: '询价单编号',
      dataIndex: 'peDocNo',
      width: 120,
      className: 'noWrap',
    }, {
      title: '当期预估用量',
      dataIndex: 'estimatedNumStr',
      width: 100,
      className: 'alignRight',
    }, {
      title: '单次起订量',
      dataIndex: 'minNumStr',
      width: 100,
      className: 'alignRight',
    }, {
      title: '含税议价',
      dataIndex: 'bargainWithTaxStr',
      width: 100,
      className: 'alignRight',
    }, {
      title: '含税报价',
      dataIndex: 'quoteWithTaxStr',
      width: 100,
      className: 'alignRight',
    }, {
      title: '议报价差异',
      dataIndex: 'marginPriceStr',
      width: 100,
      className: 'alignRight',
    }, {
      title: '税率(%)',
      dataIndex: 'taxRate',
      width: 100,
      className: 'alignRight',
    }, {
      title: '未税单价',
      dataIndex: 'netPriceStr',
      width: 100,
      className: 'alignRight',
    }, {
      title: '含税金额',
      dataIndex: 'amtStr',
      width: 100,
      className: 'alignRight',
    }, {
      title: '未税金额',
      dataIndex: 'netAmt',
      width: 100,
      className: 'alignRight',
    }, {
      title: '税额',
      dataIndex: 'taxAmtStr',
      width: 100,
      className: 'alignRight',
    }, {
      title: '最高可供应量',
      dataIndex: 'maxProvideNumStr',
      width: 100,
      className: 'alignRight',
    }, {
      title: '上期报价',
      dataIndex: 'lastPriceStr',
      width: 100,
      className: 'alignRight',
    }, {
      title: '去年同期报价',
      dataIndex: 'lastYearPriceStr',
      width: 100,
      className: 'alignRight',
    }, {
      title: '外部参考价',
      dataIndex: 'itemOuterPriceStr',
      width: 100,
      className: 'alignRight',
    }, {
      title: '上月绩效',
      dataIndex: 'scoreGrade',
      width: 100,
      className: 'noWrap',
    }, {
      title: '订货或生产周期(天)',
      dataIndex: 'orderPeriod',
      width: 100,
      className: 'alignRight',
    }, {
      title: '物流配送时间(天)',
      dataIndex: 'deliveryPeriod',
      width: 100,
      className: 'alignRight',
    }, {
      title: '备注',
      dataIndex: 'remark',
      width: 100,
      className: 'alignLeft',
    }, {
      title: '报价附件',
      dataIndex: 'quoteAttch',
      width: 500,
      className: 'alignLeft noWrap',
      render: (value, row, index) => {
        return (
          <UploadEL
            size={'small'}
            api={`/api/source-mgmt/qo/iqo/sfs/token?clsPath=${row.attachRepo}&dataKey=${row.pqmId}`}
            dataKey={row.pqmId}
            listTypes={'text'}
            disabled={true}
          />
        )
      },
    }, {
      title: '报价时间',
      dataIndex: 'quoteTime',
      width: 100,
      className: 'noWrap',
      render: (value, row, index) => {
        return (<span>{dataUtils.dtm(value)}</span>);
      },
      // fixed: 'right',
    }, {
      title: '报价状态',
      dataIndex: 'docStatusName',
      width: 80,
      // fixed: 'right',
      className: 'noWrap',
    }, {
      title: '分配比例(%)',
      dataIndex: 'percent',
      width: 120,
      required: true,
      fixed: 'right',
      className: 'alignRight',
      render: (value, row, index) => {
        const numProp = {
          min: 0,
          max: 100,
          precision: 2,
          step: 1,
          style: {width: '100%'},
          value,
        };
        return (
          <InputNumber
            {...numProp}
            onChange={(input) => {
              handleChange('percent', index, input);
            }}
          />
        );
      },
      // render: (value, row, index) => {
      //   // console.log("row==>",row)
      //   if (row.docStatus === '02') {
      //     return (<span>{value}</span>);
      //   } else {
      //     if (row.priceTime) {
      //       const numProp = {
      //         min: 0,
      //         max: 100,
      //         precision: 2,
      //         step: 0.01,
      //         style: {width: '100%'},
      //         value,
      //       };
      //       return (
      //         <InputNumber
      //           {...numProp}
      //           onChange={(input) => {
      //             handleChange('percent', index, input);
      //           }}
      //         />
      //       );
      //     } else {
      //       return (<span>{value}</span>);
      //     }

      //   }

      // },
    }, {
      title: '分配数量',
      dataIndex: 'allottedQuantityStr',
      width: 80,
      fixed: 'right',
      className: 'noWrap',
    }, {
      title: '分配金额',
      dataIndex: 'allottedAmtStr',
      width: 80,
      fixed: 'right',
      className: 'noWrap',
    }],
    buttons: [{
      key: 'confirm',
      type: 'primary',
      name: '比价确认',
      requiredSelected: 0,
      cb: (selectedRowKeys, searchBarForm, selectedRows) => {
        handleConfirm(formData);
      },
    }],
    // footer: () => {
    //   return ((formData.deadTime && formData.docStatus === '01') && <Button
    //     size="small"
    //     key="confirm"
    //     type="primary"
    //     onClick={() => {
    //       // const descriptor = {
    //       //   percent: { type: 'number', required: true, min: 0.01, max: 100, message: '分配比例(%): 必须大于0' }
    //       // };
    //       // const validator = new Schema(descriptor);
    //       // let num = 0;
    //       // for (const item of list) {
    //       //   validator.validate(item, (errors, fields) => {
    //       //     if (errors) {
    //       //       num += 1;
    //       //       return message.error(`${item.peDocNo}的${errors[0].message}`);
    //       //     }
    //       //   });
    //       //   if (num !== 0) {
    //       //     break;
    //       //   }
    //       // }
    //       // if (num === 0) {
    //       let percent = 0;
    //       list.map((item) => {
    //         if (item.percent) {
    //           percent += item.percent;
    //         }
    //       });
    //       if (percent !== 100) {
    //         return message.error('分配比例总和必须等于100%');
    //       } else {
            // dispatch({type: `${domain}/update`, payload: {list}});
    //         // console.log("=============")
    //       }
    //     }
    //     }
    //   >确认报价</Button>)
    // }
  };

  // 替代物料列
  const substituteTableProps = {
    enableSelection: false,
    scroll: {
      x: 1350,

    },
    domain,
    dispatch,
    loading,
    dataSource: substituteList,
    showAdd: false,
    showDelete: false,
    showCopy: false,
    size: 'small',
    readOnly,
    columns: [{
      title: '标准物编号',
      dataIndex: 'originItemCode',
      width: 100,
      className: 'noWrap',
    }, {
      title: '标准料名称',
      dataIndex: 'originItemName',
      width: 120,
      className: 'alignLeft',
    }, {
      title: '替代料编号',
      dataIndex: 'subItemCode',
      width: 100,
      className: 'noWrap',
    }, {
      title: '替代料名称',
      dataIndex: 'subItemName',
      width: 120,
      className: 'noWrap',
    }, {
      title: '供应商名称',
      dataIndex: 'suppName',
      width: 150,
      className: 'alignLeft',
    }, {
      title: '供应区域',
      dataIndex: 'suppArea',
      width: 100,
      className: 'noWrap',
    }, {
      title: '含税单价',
      dataIndex: 'priceWithTax',
      width: 100,
      className: 'alignRight',
    }, {
      title: '价格期间',
      dataIndex: 'priceInterval',
      width: 100,
      className: 'alignRight',
    }, {
      title: '来源区分',
      dataIndex: 'srcDocClsDesc',
      width: 100,
      className: 'alignRight',
    }, {
      title: '来源单号',
      dataIndex: 'srcDocNo',
      width: 100,
      className: 'alignRight',
    }
      // {
      //   title: '未税单价',
      //   dataIndex: 'netPrice',
      //   width: 100,
      //   className: 'alignRight',
      // }, {
      //   title: '含税金额',
      //   dataIndex: 'amt',
      //   width: 100,
      //   className: 'alignRight',
      // }, {
      //   title: '未税金额',
      //   dataIndex: 'netAmt',
      //   width: 100,
      //   className: 'alignRight',
      // }, {
      //   title: '税额',
      //   dataIndex: 'taxAmt',
      //   width: 100,
      //   className: 'alignRight',
      // }, {
      //   title: '最高可供应量',
      //   dataIndex: 'maxProvideNum',
      //   width: 150,
      //   className: 'alignRight',
      // }, {
      //   title: '价格生效日',
      //   dataIndex: 'fromDate',
      //   width: 100,
      //   className: 'noWrap',
      //   render: (value, row, index) => {
      //     return (<span>{dataUtils.ymd(value)}</span>);
      //   }
      // }, {
      //   title: '价格失效日',
      //   dataIndex: 'toDate',
      //   width: 100,
      //   className: 'noWrap',
      //   render: (value, row, index) => {
      //     return (<span>{dataUtils.ymd(value)}</span>);
      //   }
      // }, {
      //   title: '订货或生产周期(天)',
      //   dataIndex: 'orderPeriod',
      //   width: 100,
      //   className: 'alignRight',
      // }, {
      //   title: '物流配送时间(天)',
      //   dataIndex: 'deliveryPeriod',
      //   width: 100,
      //   className: 'alignRight',
      // }, {
      //   title: '备注',
      //   dataIndex: 'remark',
      //   width: 100,
      //   className: 'alignLeft',
      // }, {
      //   title: '报价时间',
      //   dataIndex: 'priceTime',
      //   width: 100,
      //   render: (value, row, index) => {
      //     return (<span>{dataUtils.dtm(value)}</span>);
      //   },
      //   className: 'noWrap',
      // }, {
      //   title: '报价状态',
      //   dataIndex: 'docStatusName',
      //   width: 100,
      //   className: 'noWrap',
      // }, {
      //   title: '分配比例(%)',
      //   dataIndex: 'percent',
      //   width: 100,
      //   className: 'alignRight',
      // }
    ],
  };

  return (
    <div style={{height: '100%'}}>
      <Toolbar
        buttons={[]}
        defId={formData.defId}
        handleCancel={handleCancel}
        loading={loading}
        mode={mode}
        prcId={formData.prcId}
        record={{}}
      />
      <Card title="询价单信息" id="basic">
        <FormEL items={basic} record={formData} readOnly={readOnly} onFieldsChange={handleFormChange}/>
      </Card>

      <Card title="整体比价结果列表" id="material">
        <EditableDataTable {...tableProps} />
      </Card>

      <Card title="替代物料参考列表" id="substitute">
        <EditableDataTable {...substituteTableProps} />
      </Card>
    </div>);
};

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