import React from 'react';
import * as tenderService from '../../../services/source/tenders';
import { ItemPicker, GroupPicker } from '@bizComponents';
import { SuggestSelect, UdcSelect } from '@components';
import { dataUtils, enums, formUtils } from '@utils';
import { DatePicker, Input, InputNumber, Modal } from 'antd';
import moment from 'moment';
import SupplierPicker from '../SupplierPicker';
import { numberUtils } from '@utils';

const TextArea = Input.TextArea;
const confirm = Modal.confirm;
const config = (formData, mode, dispatch, loading, extraInfo) => {
  // console.log('extraInfo=>',extraInfo)
  const domain = 'tenderDetails';

  const disabledEndDate = (current) => {
    if (!current) {
      return false;
    }
    return current < moment().startOf("day");
  };

  /**
   * 控制 时（HOUR） 选择，只能选择 大于等于 value 的 HOUR
   * @param current 类型：moment 当前插件选中的时间
   * @param value 类型：moment 指定的可选起始时间，只能选择大于等于value的时间
   */
  const disabledHours = (current, value) => {
    if (current.year() === value.year()
      && current.month() === value.month()
      && current.date() === value.date()) {
      return range(0, 24).splice(0, value.hours())
    } else {
      return []
    }
  };

  /**
   * 控制 分钟（MINUTES） 选择，只能选择 大于等于 value 的 MINUTES
   * @param current 类型：moment 当前插件选中的时间
   * @param value 类型：moment 指定的可选起始时间，只能选择大于等于value的时间
   */
  const disabledMinutes = (current, value) => {
    if (current.year() === value.year()
        && current.month() === value.month()
        && current.date() === value.date()
        && current.hours() === value.hours()) {
      return range(0, 60).splice( 0, value.minutes());
    } else {
      return []
    }
  };

  /**
   * 控制 秒（SECONDS） 选择，只能选择 大于等于 value 的 SECONDS
   * @param current 类型：moment 当前插件选中的时间
   * @param value 类型：moment 指定的可选起始时间，只能选择大于等于value的时间
   */
  const disabledSeconds = (current, value) => {
    if (current.year() === value.year()
      && current.month() === value.month()
      && current.date() === value.date()
      && current.hours() === value.hours()
      && current.minutes() === value.minutes()) {
      return range(0, 60).splice( 0, value.seconds());
    } else {
      return []
    }
  };

  const disabledEndTime = (current) => {
    if (!current) {
      current = moment();
    }
    return {
      disabledHours: () => disabledHours(current, moment()),
      disabledMinutes: () => disabledMinutes(current, moment()),
      disabledSeconds: () => disabledSeconds(current, moment())
    }
  };

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

  const disabledOpenDate = (current) => {
    if (!current) {
      return false;
    }
    if (formData && formData.deadlineTime) {
      const deadline = moment.isMoment(formData.deadlineTime)
        ? formData.deadlineTime
        : moment(formData.deadlineTime);
      return current < deadline;
    } else {
      return current < moment().startOf("day");
    }
  };

  function range(start, end) {
    const result = [];
    for (let i = start; i < end; i++) {
      result.push(i);
    }
    return result;
  }

  function getDeadlineMoment() {
    const { deadlineTime } = formData;
    return moment.isMoment(deadlineTime) ? deadlineTime : moment(deadlineTime);
  }

  function disabledOpenTime(current) {

    let value;
    if (formData && formData.deadlineTime) {
      value = moment.isMoment(formData.deadlineTime)
        ? formData.deadlineTime
        : moment(formData.deadlineTime);
    } else {
      value = moment();
    }

    if (!current) {
      current = value;
    }

    return {
      disabledHours: () => disabledHours(current, value),
      disabledMinutes: () => disabledMinutes(current, value),
      disabledSeconds: () => disabledSeconds(current, value),
    };
  }


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

  // 物料选择改变事件
  const onMaterialChange = async (value, index) => {
    console.log("value",value);
    console.log("index",index);
    const items = value; // 已选物料
    if (items) {
      const { suppList } = extraInfo;
      const suppIds = suppList.map(i => i.suppId); // 已选供应商
      const result = await tenderService.itemCheck({ items: items, suppIds: suppIds });
      if (result.success && result.data.length > 0) {
        //接口调用成功 && 存在不满足物料需求的供应商
        let warnMsg: string = '';
        let suppMap = new Map();
        for (let check of result.data) {
          if (suppMap.has(check.suppName)) {
            suppMap.set(check.suppName, `${suppMap.get(check.suppName)}、${check.itemName}`);
          } else {
            suppMap.set(check.suppName, `${check.itemName}`);
          }
        }
        suppMap.forEach((value, key) => {
          warnMsg += `${key} 无法提供物料: ${value};  \n`;
        });
        const removeSuppId = result.data.map(i => i.suppId);
        confirm({
          title: '以下供应商不具备指定物料的供应能力，添加该物料会移除这些供应商：',
          content: warnMsg,
          okText: '确认添加',
          cancelText: '取消',
          onOk() {
            dispatch({ type: `${domain}/updateMaterial`, payload: { value, index } });
            dispatch({ type: `${domain}/removeSupp`, payload: { suppIds: removeSuppId } });
          },
          onCancel() {
            dispatch({ type: `${domain}/removeItem`, payload: { index } });
          }
        });
      } else {
        dispatch({ type: `${domain}/updateMaterial`, payload: { value, index } });
      }
    } else {
      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 } });
  };

  // 基本信息form
  const tenderBasicForm = [
    {
      title: '招标单号',
      dataIndex: 'docNo',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: <Input disabled={true} placeholder="系统自动生成"/>,
    }, {
      title: '招标方式',
      dataIndex: 'biType',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: <UdcSelect domain="SRM" code="BID_MODE"/>,
    }, {
      title: '供货区域',//todo 改变后应该清空供应商
      dataIndex: 'suppCenterId',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: <SuggestSelect apiName="regions"/>,
    }, {
      title: '招标名称',
      dataIndex: 'biName',
      options: {
        rules: [
          {
            required: false,
            whitespace: true,
            message: '必填',

          },
          {
            min: 1,
            max: 50,
            message: '不能超过50个字',
          },
        ],
      },
      tag: <Input/>,
    }, {
      title: '招标负责人',
      dataIndex: 'personInCharge',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
          {
            min: 1,
            max: 40,
            message: '不能超过40个字',
          },
        ],
      },
      tag: <Input/>,
    }, {
      title: '负责人电话',
      dataIndex: 'tel',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
          {
            min: 1,
            max: 40,
            message: '不能超过40个字',
          },
        ],
      },
      tag: <Input/>,
    }, {
      title: '价格生效日',
      dataIndex: 'bidFromDate',
      tag: <DatePicker style={{ width: '100%' }} disabledDate={disabledEndDate}/>,
      options: {
        rules: [
          {
            required: true,
            message: '请选择价格生效日',
          },
        ],
      },
    },{
      title: '价格失效日',
      dataIndex: 'bidToDate',
      tag: <DatePicker style={{ width: '100%' }} disabled={!(formData.bidFromDate)} disabledDate={disabledBidEndDate}/>,
      options: {
        rules: [
          {
            required: true,
            message: '请选择价格失效日',
          },
        ],
      },
    }, {
      title: '投标截止时间',
      dataIndex: 'deadlineTime',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: <DatePicker style={{ width: '100%' }}
                       showTime
                       format="YYYY-MM-DD HH:mm:ss"
                       disabledDate={disabledEndDate}
                       disabledTime={disabledEndTime}/>,
    }, {
      title: '开标时间',
      dataIndex: 'bidOpenTime',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: <DatePicker
              style={{ width: '100%' }}
              showTime
              format="YYYY-MM-DD HH:mm:ss"
              disabledDate={disabledOpenDate}
              disabledTime={disabledOpenTime}
           />,
    }, {
      title: '保证金',
      dataIndex: 'cashDeposit',
      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, '')}
        style={{width:'100%'}}
      />,
    }, {
      title: '有效投标数',
      dataIndex: 'bidTimes',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: <InputNumber
        min={1}
        max={100}
        precision={0}
        style={{width:'100%'}}
      />,
    }, {
      title: '注册资金最低',
      dataIndex: 'minRegFund',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: <Input addonAfter="万元"/>,
    }, {
      title: '公司运营时间最少',
      dataIndex: 'minOperDays',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: <Input addonAfter="天"/>,
    }, {
      title: '质量说明',
      dataIndex: 'qualityMemo',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: <TextArea autosize={{ minRows: 3, maxRows: 3 }} maxLength={300} style={{ marginBottom: 3 }}/>,
    }, {
      title: '证照资质说明',
      dataIndex: 'certMemo',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: <TextArea autosize={{ minRows: 3, maxRows: 3 }} maxLength={300} style={{ marginBottom: 3 }}/>,
    }, {
      title: '供应商资格说明',
      dataIndex: 'qualificationMemo',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: <TextArea autosize={{ minRows: 3, maxRows: 3 }} maxLength={300}/>,
    }, {
      title: '招标条件',
      dataIndex: 'conditionMemo',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: <TextArea autosize={{ minRows: 3, maxRows: 3 }} maxLength={300}/>,
    }, {
      title: '备注',
      dataIndex: 'memo',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: <TextArea autosize={{ minRows: 3, maxRows: 3 }} maxLength={500}/>,
    }, {
      title: '招标单状态',
      dataIndex: 'docStatus',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: <UdcSelect domain="SRM" code="BID_INVITING_STATUS" disabled={true}/>,
    }];
  // 物料
  const tenderMaterialList = [
    {
      title: '物料名称',
      dataIndex: 'itemDesc',
      width: 150,
      className: 'alignLeft',
      render: (value, row, index) => {// 状态为正式和新物料
        return (
          <ItemPicker
            type="multiple"
            filter={{ statusList: [0, 2] }}
            size="small"
            apiName="suppItems"
            style={{ width: '60%', textAlign: 'left' }}
            value={{ id: row.itemId, code: row.itemCode, name: row.itemDesc }}
            onChange={(inputValue) => onMaterialChange(inputValue, index)}
          />
        );
      },
    },
    {
      title: '物料编号',
      dataIndex: 'itemCode',
      width: 100,
      className: 'noWrap',
    }, {
      title: '物料规格',
      dataIndex: 'itemSpec',
      width: 150,
      className: 'alignLeft',
    }, {
      title: '单位',
      dataIndex: 'itemUomName',
      width: 80,
    }, {
      title: '数量',
      dataIndex: 'itemQty',
      width: 100,
      render: (value, row, index) => {
        return (
          <InputNumber
            min={0}
            max={999999999999}
            precision={2}
            size="small"
            value={value}
            onChange={(e) => {
              handleChange('itemQty', index, e);
            }}
          />
        );
      },
    },{
      title: '评标基准价',
      dataIndex: 'bidBasePrice',
      width: 100,
      hidden: extraInfo? extraInfo.suppFlag:true,
      formatter: numberUtils.round_half_up_format,
      precision: 4,
      render: (value, row, index) => {
        return (
          <InputNumber
            min={0}
            max={999999999999}
            precision={4}
            step={0.0001}
            size="small"
            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, '')}
            onChange={(e) => {
              handleChange('bidBasePrice', index, e);
            }}
          />
        );
      },
    },];
  //评标小组
  const tenderTeamForm = [
    {
      title: '评标小组',
      dataIndex: 'group',
      options: {
        rules: [
          {
            required: false,
            message: '必填',
          },
        ],
      },
      tag: (extraInfo && extraInfo.c3code) ? (
        <GroupPicker filter={{itemC3Code: extraInfo.c3code }}/>
      ):(<GroupPicker disabled="true"/>),
    }];
  // 供应商
  const tenderSupplierList = [
    {
    title: '供应商名称',
    dataIndex: 'suppName',
    width: '25%',
    className: 'alignLeft',
    required: true,
    render: (value, row, index) => {

      return (extraInfo && extraInfo.suppCenterId) && (
        <SupplierPicker
          filter={{
            region: extraInfo ? extraInfo.suppCenterId : null,
            suppStatusList: ['02'],
            itemCodes: extraInfo ? extraInfo.itemCodes : []
          }}
          value={{ id: row.suppId, code: row.suppCode, name: row.suppName }}
          size="small"
          onChange={(inputValue) => onSuppChange(inputValue, index)}
        />);
    },
  }, {
    title: '供应商编号',
    dataIndex: 'suppCode',
    width: '20%',
    className: 'noWrap',
  }, {
    title: '供应商状态',
    dataIndex: 'suppStatusName',
    width: '15%',
    className: 'noWrap',
  }, {
    title: '上月绩效',
    dataIndex: 'lastGrade',
    width: '13%',
    className: 'noWrap',
  }, {
    title: '上上月绩效',
    dataIndex: 'lastGrade2',
    width: '13%',
    className: 'noWrap',
  }, {
    title: '上上上月绩效',
    dataIndex: 'lastGrade3',
    width: '13%',
    className: 'noWrap',
  }];

  return {
    tenderBasicForm,
    tenderMaterialList,
    tenderTeamForm,
    tenderSupplierList,
  };
};

export default config;
