import React from 'react';

import { ItemPicker, OuPicker, SupplierPicker } from '@bizComponents';
import { SuggestSelect, UdcSelect } from '@components';
import { dataUtils, enums, formUtils } from '@utils';
import { numberUtils } from '@utils';
import { DatePicker, Input, InputNumber, Select } from 'antd';
import moment from 'moment';
import styles from './styles.less';
const Option = Select.Option;
const { pqdStatus } = enums;
const config = (formData, mode, dispatch, loading, extraInfo) => {
  const domain = 'inquiryDetails';
  const disabledEndDate = (endValue) => {
    if (!endValue) {
      return false;
    }
    // console.log("endvalue==>",endValue.valueOf())
    // console.log("moment==>",moment().valueOf())
    return endValue.valueOf() <= moment().valueOf();
  };
  const disabledDate = (current) => {
    // Can not select days before today and today
    return current && current < moment().endOf('day');
  };

  const disabledPriceExpireDate = (endValue) => {
    if (!endValue) {
      return false;
    }
    if (formData && formData.priceEffectDate) {
      return endValue.valueOf() < formData.priceEffectDate;
    } else {
      return endValue.valueOf() < moment().valueOf();
    }
  };

  // const changeQuoteType  = (value) => {
  //   dispatch({ type: `${domain}/updateQuoteType`, payload: { value } })
  // }

  // 公司选择改变事件
  // const onOuChange = (value) => {
  //   // console.log("ou==>",value)
  //   dispatch({ type: `${domain}/updateOu`, payload: { value } })
  // }

  // 供应商选择改变事件
  const onSuppChange = (value, index) => {
    // console.log(value)
    // console.log('supp==>',extraInfo)
    dispatch({ type: `${domain}/updateSupp`, payload: { value, index } });
  };

  // 物料选择改变事件
  const onMaterialChange = (value, index) => {
    dispatch({ type: `${domain}/updateMaterial`, payload: { value, index } });
  };

  /**
   * @param key      字段名
   * @param index    行号
   * @param newValue 新值
   */
  const handleChange = (key, index, newValue) => {
    dispatch({ type: `${domain}/updateCell`, payload: { key, index, value: newValue } });
  };

  /**
   * 获得焦点，因为点击InputNumber中的上下按钮调用的实际上是onChange方法，不会获得焦点，导致无法调用最终的onBlur方法，所以先写一个获得焦点的方法
   * @param inputRef
   * @param defaultValue
   */
  const setFocus = (inputRef, defaultValue) => (value) => {
    console.log("inputRef",inputRef);
    console.log("defaultValue",defaultValue);
    console.log("value",value);
    // 不清楚具体原理，但是如果修改的值和原值相等，就会再调用一次onChange方法，如果这里不做判断，就会导致无限获取焦点，鼠标光标出不来了
    if (defaultValue !== value) {
      inputRef.current.focus();
    }
  };

  const handleUpdateNumberCell = (key, index) => (value) => {
    handleChange(key, index, value.target.value ? parseFloat(value.target.value.replace(',', '')) : null);
  };

  const handleUpdateTextCell = (key, index) => (value) => {
    handleChange(key, index, value.target.value ? value.target.value : null);
  };

  const numberFormatter = (value) => {
      var parts = value.toString().split(".");
      parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
      return parts.join(".");
    // return numberUtils.round_half_up_format(value, precision);
  };

  // 基本信息form
  const inquiryBasicForm = [
    {
      title: '询价单编号',
      dataIndex: 'docNo',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: <Input disabled={true} placeholder="系统自动生成"/>,
    }, {
      title: '项目名称',
      dataIndex: 'peName',
      options: {
        rules: [
          {
            required: false,
            whitespace: true,
            message: '必填',

          },
          {
            min: 1,
            max: 50,
            message: '不能超过50个字',
          },
        ],
      },
      tag: <Input/>,
    }, {
      title: '供货区域',
      dataIndex: 'suppCenterId',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: <SuggestSelect apiName="regions"/>,
    },
    // {
    //   title: '收货公司',
    //   dataIndex: 'recCompany',
    //   options: {
    //     rules: [
    //       {
    //         required: false,
    //         message: '必填',
    //       },
    //     ],
    //   },
    //   tag: <OuPicker/>
    // }, {
    //   title: '收货地址',
    //   dataIndex: 'recCompanyAddress',
    //   options: {
    //     rules: [
    //       {
    //         required: false,
    //         whitespace: true,
    //         message: '必填',
    //       },
    //       {
    //         min: 1,
    //         max: 200,
    //         message: '不能超过200个字',
    //       },
    //     ],
    //   },
    //   tag: <Input/>,
    // },
    {
      title: '询价方式',
      dataIndex: 'quoteType',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: <UdcSelect domain="SRM" code="PE_MODE"/>,
    }, {
        title: '询价周期',
        dataIndex: 'quotePeriod',
        tag: <UdcSelect domain="SRM" code="PERIOD_MONTH"/>,
      }, {
        title: '价格生效日',
        dataIndex: 'priceEffectDate',
        options: {
          rules: [
            {
              required: false,
              message: '必填',
            },
          ],
        },
        tag: (<DatePicker style={{ width: '100%' }} format="YYYY-MM-DD"/>),
      }, {
        title: '价格失效日',
        dataIndex: 'priceExpireDate',
        options: {
          rules: [
            {
              required: false,
              message: '必填',
            },
          ],
        },
        tag: (<DatePicker style={{ width: '100%' }} format="YYYY-MM-DD" disabled={!formData.priceEffectDate} disabledDate={disabledPriceExpireDate}/>),
      }, {
        title: '报价截止时间',
        dataIndex: 'deadlineTime',
        options: {
          rules: [
            {
              required: false,
              message: '必填',
            },
          ],
        },
        tag: (<DatePicker style={{ width: '100%' }} showTime format="YYYY-MM-DD HH:mm:ss" disabledDate={disabledEndDate}/>),
      }, {
        title: '议价截止时间(小时)',
        dataIndex: 'deadlineHour',
        options: {
          rules: [
            {
              required: false,
              message: '必填',
            },
          ],
        },
        tag: <InputNumber style={{ width: '100%' }} precision={0} min={1} max={formData.docStatus === '04' ? 2000 : 48}/>,
    }, {
      title: '询价状态',
      dataIndex: 'docStatus',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: <UdcSelect domain="SRM" code="PE_STATUS" disabled={true}/>,
    }, {
      title: '制单人',
      dataIndex: 'createUser',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: <Input disabled={true}/>,
    }, {
      title: '制单公司',
      dataIndex: 'createCompany',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: <Input disabled={true}/>,
    }, {
      title: '制单人电话',
      dataIndex: 'createTel',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: <Input disabled={true}/>,
    }, {
      title: '创建日期',
      dataIndex: 'createDate',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: <DatePicker style={{ width: '100%' }} disabled={true} format="YYYY-MM-DD"/>,
    }, {
        title:'报价后即可见',
        dataIndex: 'reviewFlag',
        hidden: true,   //需求：这个内容不需要了
        options: {
          rules: [
            {
              required: false,
              message: '必填',
            },
          ],
        },
        tag:(
          <Select defaultActiveFirstOption={true}
                  style={{ width: '100%' }}
                  filterOption={false}>
            <Option value="0" >否</Option>
            <Option value="1" >是</Option>
          </Select>
        )
    }];
  // 供应商
  const inquirySupplierList = [
    {
      title: '供应商名称',
      dataIndex: 'suppName',
      width: '10%',
      className: 'alignLeft',
      required: true,
      render: (value, row, index) => {

        return (extraInfo && extraInfo.suppCenterId) && (
          <SupplierPicker
            filter={{ region: extraInfo ? extraInfo.suppCenterId : null, suppStatusList: ['02'] }}
            value={{ id: row.suppId, code: row.suppCode, name: row.suppName }}
            size="small"
            onChange={(inputValue) => onSuppChange(inputValue, index)}
          />);
      },
    }, {
      title: '供应商编号',
      dataIndex: 'suppCode',
      width: '8%',
      className: 'noWrap',
    }, {
      title: '供应商状态',
      dataIndex: 'suppStatusName',
      width: '6%',
      className: 'noWrap',
    }, {
      title: '最新绩效',
      dataIndex: 'scoreGrade',
      width: '6%',
      className: 'noWrap',
    }, {
      title: '联系人',
      dataIndex: 'suppLinkMan',
      width: '6%',
      className: 'alignLeft',
    }, {
      title: '联系人电话',
      dataIndex: 'suppLinkTel',
      width: '8%',
      className: 'noWrap',
    }, {
      title: '结款方式',
      dataIndex: 'cashMethodName',
      width: '6%',
      className: 'noWrap',
    }/*,{
      title: '税种',
      dataIndex: 'taxClass',
      width: '4%',
      className: 'noWrap',
    }*/, {
      title: '税率(%)',
      dataIndex: 'taxRate',
      width: '4%',
      className: 'alignRight',
    },
  ];
  // 物料
  const inquiryMaterialList = [
    {
      title: '物料编号',
      dataIndex: 'itemCode',
      width: 100,
      fixed: 'left',
      className: 'noWrap',
    }, {
      title: '物料名称',
      dataIndex: 'itemDesc',
      width: 170,
      fixed: 'left',
      className: 'alignLeft',
      render: (value, row, index) => {// 状态为正式和新物料
        return(extraInfo && extraInfo.suppCenterId) && (
          <ItemPicker
            type="multiple"
            filter={{ statusList: [0, 2], suppId: extraInfo.suppId }}
            size="small"
            apiName="items"
            style={{ width: '60%', textAlign: 'left' }}
            value={{ id: row.itemId, code: row.itemCode, name: row.itemDesc }}
            onChange={(inputValue) => onMaterialChange(inputValue, index)}
          />
        );
      },
    }, {
      title: '物料品牌',
      dataIndex: 'itemBrand',
      width: 100,
      fixed: 'left',
      className: 'alignLeft',
    }, {
      title: '物料规格',
      dataIndex: 'itemSpec',
      width: 160,
      fixed: 'left',
      className: 'alignLeft',
    }, {
      title: '单位',
      dataIndex: 'itemUomName',
      width: 80,
      fixed: 'left',
      className: 'alignLeft',
    // },{
    //   title: '价格生效日',
    //   dataIndex: 'fromDate',
    //   width: 130,
    //   className: 'noWrap',
    //   render: (value, row, index) => {
    //     return (
    //       <DatePicker
    //         style={{ width: '100%' }}
    //         value={value ? moment(value) : null}
    //         format="YYYY-MM-DD"
    //         size="small"
    //         disabledDate={disabledEndDate}
    //         onChange={(e) => {   handleChange('fromDate', index, e);  }}
    //       />
    //     );
    //   },
    // }, {
    //   title: '价格失效日',
    //   dataIndex: 'toDate',
    //   width: 100,
    //   className: 'noWrap',
    //   render: (value, row, index) => {
    //     return (<span>{dataUtils.ymd(value)}</span>);
    //   }
    }, {
      title: '未税基准价',
      dataIndex: 'guidePrice',
      width: 120,
      className: 'alignRight',
      formatter: numberUtils.round_half_up_format,
      precision: 4,
      render: (value, row, index) => {
        const inputRef = React.createRef();
        return (
          <InputNumber
            ref={inputRef}
            //disabled={true}
            min={0}
            max={999999999999}
            precision={4}
            step={0.0001}
            size="small"
            defaultValue={value}
            formatter={numberFormatter}
            parser={(value) => value.replace(/(,*)/g, '')}
            onChange={setFocus(inputRef, value)}
            onBlur={handleUpdateNumberCell('guidePrice', index)}
          />
        );
      },
    }, {
      title: '税率',
      dataIndex: 'taxRate',
      width: 200,
      render: (value, row, index) => {
        return (
          <Select
            style={{ width: '100%' }}
            disabled={!extraInfo.editMaterialFlag}
            defaultActiveFirstOption={true}
            onChange={(v, e) => {  handleChange('taxRate', index, v); }}
            value={value}>
            {(extraInfo && extraInfo.taxList) && extraInfo.taxList.map(s => <Option value={s.taxRate}>{s.taxDesc}</Option>)}
          </Select>
        );
      },
    }, {
      title: '含税报价(元)',
      dataIndex: 'taxPrice',
      width: 120,
      className: 'alignRight',
      formatter: numberUtils.round_half_up_format,
      precision: 4,
      render: (value, row, index) => {
        const inputRef = React.createRef();
        return (
          <InputNumber
            ref={inputRef}
            disabled={row.docStatus === pqdStatus.COMFIRM}
            size="small"
            min={0}
            max={999999999999}
            precision={4}
            step={0.0001}
            defaultValue={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, '')}
            // onChange={(e) => {  handleChange('taxPrice', index, e); }}
            onChange={setFocus(inputRef, value)}
            formatter={numberFormatter}
            onBlur={handleUpdateNumberCell('taxPrice', index)}
          />
        );
      },
    }, {
      title: '含税议价(元)',
      dataIndex: 'yjPrice',
      width: 120,
      className: 'alignRight',
      formatter: numberUtils.round_half_up_format,
      precision: 4,
      render: (value, row, index) => {
        const inputRef = React.createRef();
        return (
          <InputNumber
            ref={inputRef}
            disabled={row.docStatus === pqdStatus.COMFIRM || row.docStatus === pqdStatus.NO_ACCEPT}
            size="small"
            min={0}
            max={999999999999}
            precision={4}
            step={0.0001}
            defaultValue={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, '')}
            // onChange={(e) => {  handleChange('yjPrice', index, e); }}
            onChange={setFocus(inputRef, value)}
            formatter={numberFormatter}
            onBlur={handleUpdateNumberCell('yjPrice', index)}
          />
        );
      },
    }, {
      title: '议报价差异',
      dataIndex: 'gapPrice',
      width: 120,
      className: 'alignRight',
      render: (value, row, index) => {
        return (
          <span className={row.gapPrice > 0 ? styles.warningNum : ''}>{value}</span>
        )
      }
    }, {
      title: '未税降本差异金额',
      dataIndex: 'yjOverTaxprice',
      width: 120,
      className: 'alignRight',
      formatter: numberUtils.round_half_up_format,
      precision: 2,
      render: (value, row, index) => {
        return (
          <InputNumber
            disabled={true}
            size="small"
            precision={2}
            step={0.01}
            value={value}
            formatter={numberFormatter}
            parser={(value) => value.replace(/(,*)/g, '')}
          />
        );
      },
    }, {
      title: '分配比例(%)',
      dataIndex: 'proportion',
      width: 120,
      className: 'alignRight',
    },{
      title: '分配数量',
      dataIndex: 'allowedNumber',
      width: 120,
      className: 'alignRight',
    },{
      title: '分配金额',
      dataIndex: 'allowedAmtStr',
      width: 120,
      className: 'alignRight',
    },{
      title: '当期预估用量',
      dataIndex: 'estimatedNum',
      width: 120,
      className: 'alignRight',
      render: (value, row, index) => {
        const inputRef = React.createRef();
        return (
          <InputNumber
            ref={inputRef}
            min={0}
            max={999999999999}
            precision={2}
            step={0.01}
            size="small"
            defaultValue={value}
            // onChange={(e) => { handleChange('estimatedNum', index, e); }}
            onChange={setFocus(inputRef, value)}
            onBlur={handleUpdateNumberCell('estimatedNum', index)}
          />
        );
      },
    },  {
      title: '单次起订量',
      dataIndex: 'minNum',
      width: 120,
      className: 'alignRight',
      render: (value, row, index) => {
        const inputRef = React.createRef();
        return (
          <InputNumber
            ref={inputRef}
            disabled={row.docStatus === pqdStatus.COMFIRM}
            min={0}
            max={999999999999}
            precision={2}
            step={0.01}
            size="small"
            defaultValue={value}
            // onChange={(e) => {  handleChange('minNum', index, e); }}
            onChange={setFocus(inputRef, value)}
            onBlur={handleUpdateNumberCell('minNum', index)}
          />
        );
      },
    }, {
      title: '税额(元)',
      dataIndex: 'taxAmt',
      width: 120,
      className: 'alignRight',
      formatter: numberUtils.round_half_up_format,
      precision: 2,
      render: (value, row, index) => {
        return (
          <InputNumber
            disabled={true}
            size="small"
            min={0}
            precision={2}
            step={0.01}
            value={value}
            // formatter={(value) => {
            //   var parts = value.toString().split(".");
            //   parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            //   return parts.join(".");
            // }}
            formatter={numberFormatter}
            parser={(value) => value.replace(/(,*)/g, '')}
          />
        );
      },
    }, {
      title: '含税金额(元)',
      dataIndex: 'amt',
      width: 120,
      className: 'alignRight',
      formatter: numberUtils.round_half_up_format,
      precision: 2,
      render: (value, row, index) => {
        return (
          <InputNumber
            disabled={true}
            size="small"
            min={0}
            precision={2}
            step={0.01}
            value={value}
            // formatter={(value) => {
            //   var parts = value.toString().split(".");
            //   parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            //   return parts.join(".");
            // }}
            formatter={numberFormatter}
            parser={(value) => value.replace(/(,*)/g, '')}
          />
        );
      },
    }, {
      title: '未税单价(元)',
      dataIndex: 'netPrice',
      width: 120,
      className: 'alignRight',
      formatter: numberUtils.round_half_up_format,
      precision: 4,
      render: (value, row, index) => {
        return (
          <InputNumber
            disabled={true}
            size="small"
            min={0}
            precision={4}
            step={0.0001}
            value={value}
            // formatter={(value) => {
            //   var parts = value.toString().split(".");
            //   parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            //   return parts.join(".");
            // }}
            formatter={numberFormatter}
            parser={(value) => value.replace(/(,*)/g, '')}
          />
        );
      },
    }, {
      title: '未税金额(元)',
      dataIndex: 'netAmt',
      width: 120,
      className: 'alignRight',
      formatter: numberUtils.round_half_up_format,
      precision: 2,
      render: (value, row, index) => {
        return (
          <InputNumber
            disabled={true}
            size="small"
            min={0}
            precision={2}
            step={0.01}
            value={value}
            // formatter={(value) => {
            //   var parts = value.toString().split(".");
            //   parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ",");
            //   return parts.join(".");
            // }}
            formatter={numberFormatter}
            parser={(value) => value.replace(/(,*)/g, '')}
          />
        );
      },
    }, {
      title: '最高可供应量',
      dataIndex: 'maxProvideNum',
      width: 120,
      className: 'alignRight',
      render: (value, row, index) => {
        const inputRef = React.createRef();
        return (
          <InputNumber
            ref={inputRef}
            disabled={row.docStatus === pqdStatus.COMFIRM}
            size="small"
            defaultValue={value}
            min={0}
            max={999999999999}
            precision={2}
            step={0.01}
            // onChange={(e) => {  handleChange('maxProvideNum', index, e); }}
            onChange={setFocus(inputRef, value)}
            onBlur={handleUpdateNumberCell('maxProvideNum', index)}
          />
        );
      },
    },  {
      title: '订货或生产周期(天)',
      dataIndex: 'orderPeriod',
      width: 120,
      className: 'alignRight',
      render: (value, row, index) => {
        const inputRef = React.createRef();
        return (
          <InputNumber
            ref={inputRef}
            disabled={row.docStatus === pqdStatus.COMFIRM}
            size="small"
            min={0}
            max={9999}
            precision={0}
            defaultValue={value}
            // onChange={(e) => {  handleChange('orderPeriod', index, e); }}
            onChange={setFocus(inputRef, value)}
            onBlur={handleUpdateNumberCell('orderPeriod', index)}
          />
        );
      },
    }, {
      title: '物流配送时间(天)',
      dataIndex: 'deliveryPeriod',
      width: 120,
      className: 'alignRight',
      render: (value, row, index) => {
        const inputRef = React.createRef();
        return (
          <InputNumber
            ref={inputRef}
            disabled={row.docStatus === pqdStatus.COMFIRM}
            size="small"
            defaultValue={value}
            min={0}
            max={9999}
            precision={0}
            // onChange={(e) => {  handleChange('deliveryPeriod', index, e); }}
            onChange={setFocus(inputRef, value)}
            onBlur={handleUpdateNumberCell('deliveryPeriod', index)}
          />
        );
      },
    }, {
      title: '备注',
      dataIndex: 'remark',
      className: 'alignLeft',
      render: (value, row, index) => {
        return (
          <Input
            disabled={row.docStatus === pqdStatus.COMFIRM}
            size="small"
            defaultValue={value}
            // onChange={(e) => {  handleChange('remark', index, e.target.value); }}
            onBlur={handleUpdateTextCell('remark', index)}
          />
        );
      },
    },
  ];
  // 报价说明
  const inquiryQuoteForm = [
    {
    //   title: '起送量',
    //   dataIndex: 'minFeedNum',
    //   options: {
    //     rules: [
    //       {
    //         required: false,
    //         message: '必填',
    //       },
    //       {
    //         min: 1,
    //         max: 40,
    //         message: '不超过40字',
    //       },
    //     ],
    //   },
    //   tag: <Input/>,
    // }, {
      title: '起送金额',
      dataIndex: 'minFeedAmt',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: (
        <InputNumber
          min={0}
          max={999999999999}
          precision={2}
          step={0.01}
          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, '')}
        />
      ),
    }, {
      title: '订货周期(天)',
      dataIndex: 'orderPeriod',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: (
        <InputNumber
          min={0}
          max={9999}
          precision={0}
        />
      ),
    // }, {
    //   title: '报价有效天数',
    //   dataIndex: 'validDay',
    //   options: {
    //     rules: [
    //       {
    //         required: false,
    //         message: '必填',
    //       },
    //     ],
    //   },
    //   tag: (
    //     <InputNumber
    //       min={0}
    //       max={99999}
    //       precision={0}
    //     />
    //   ),
    }, {
      title: '报价备注说明',
      dataIndex: 'remark',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
          {
            min: 1,
            max: 200,
            message: '不超过200字',
          },
        ],
      },
      tag: <Input/>,
    }
  ];
  return {
    inquiryBasicForm,
    inquirySupplierList,
    inquiryMaterialList,
    inquiryQuoteForm
  };
};

export default config;
