import { Block, Page, Panel, Toolbar } from '@bizComponents';
import { Loader, UploadEL } from '@components';
import { dataUtils, enums, formUtils } from '@utils';
import { Card, DatePicker, Input, message,Icon, Modal } from 'antd';
import Schema from 'async-validator';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import moment from 'moment';
import React from 'react';
import config from './tendersDetailCfg';
import styles from './styles.less';

const { entType, resultCode, bidStatus, approveStatus } = enums;
const Detail = ({ tenderDetails, tenderDetailsSupp, dispatch, loading }) => {
  const { remoteCfg, user, mode, list, mlist, formData, preBid, attachRepo, suppFlag, saveBtnFlag, bidBtnFlag } = tenderDetails;

  const domain = 'tenderDetails';
  const domainCN = '招标单详情';
  let viewFlag = true;
  const width = '20%';
  if (mode === 'view') {
    viewFlag = true;
  } else if (mode === 'create') {
    viewFlag = false;
  } else if (mode === 'update') {
    viewFlag = false;
  } else if (mode === 'approve') {
    viewFlag = true;
  } else {
    // nothing...
  }

  // 供应商列
  const supplierTableProps = {
    rowKey: 'id',
    scroll: {
      x: '100%',
      y: 500,
    },
    domain: 'tenderDetailsSupp',
    dispatch,
    loading,
    // dataSource: list,
    showAdd: !suppFlag,
    showDelete: !suppFlag,
    showCopy: false,
    size: 'small',
    // enableSelection: false,
    // footer: null,
    // readOnly,
    // columns: [],
  };

  // 物料列
  const materialTableProps = {
    rowKey: 'id',
    scroll: {
      x: 700,
      y: 500,
    },
    domain,
    dispatch,
    loading,
    // dataSource: mlist,
    // showAdd: false,
    // showDelete: false,
    showCopy: false,
    size: 'small',
    // enableSelection: false,
    // readOnly,
    // columns: [],
  };


  const handleFormChange = (field) => {
    const key = Object.keys(field)[0];
    if(key === 'group'){
      const value = field[key];
      dispatch({
        type: `${domain}/updateForm`,
        payload: {
          key,
          value: value,
        },
      });
      dispatch({
        type: `${domain}/updateForm`,
        payload: {
          key :'groupId',
          value: value.id,
        },
      });
    }else{
      dispatch({
        type: `${domain}/updateForm`,
        payload: {
          key,
          value: field[key],
        },
      });
    }
    if (key === 'deadlineTime') {
      dispatch({ type: `${domain}/updateForm`, payload: { key: 'bidOpenTime', value: null } });
    }

  };


  const getFormRules = () => {
    //todo 评标小组校验
    const remoteData = remoteCfg.panels.find((x) => {
      return x.panelId === 'tenderBasic';
    }).blocks.find((y) => {
      return y.blockId === 'tenderBasicForm';
    }).fields;
    const newFormData = config(formData, mode, dispatch, loading, {}).tenderBasicForm.slice();
    newFormData.forEach((item) => {
      const remoteItem = remoteData.find((z) => {
        return z.fieldId === item.dataIndex;
      });
      if (remoteItem.required === 1) {
        item.options.rules[0].required = true;
      }
    });
    const remoteGroupData = remoteCfg.panels.find((x) => {
      return x.panelId === 'tenderTeam';
    }).blocks.find((y) => {
      return y.blockId === 'tenderTeamForm';
    }).fields;
    const newFormData2 = config(formData, mode, dispatch, loading, {}).tenderTeamForm.slice();
    newFormData2.forEach((item) => {
      const remoteItem = remoteGroupData.find((z) => {
        return z.fieldId === item.dataIndex;
      });
      if (remoteItem.required === 1) {
        item.options.rules[0].required = true;
      }
    });
    return newFormData.concat(newFormData2);
  };

  const validateItem = () => {
    let itemDescriptor = {
      itemDesc: { type: 'string', required: true, message: '物料名称：必填' },
      itemId: { type: 'number', required: true, message: '物料：必选' },
      itemQty: { type: 'number', required: true, message: '数量：必填' },
      bidBasePrice: { type: 'number', required: true, message: '评标基准价：必填' },
    };
    const itemValidator = new Schema(itemDescriptor);
    if (mlist.length > 0) {
      let num = 0;
      for (const item of mlist) {
        // console.log('item==>',item)
        itemValidator.validate(item, (errors, fields) => {
          if (errors) {
            num += 1;
            message.error(`${errors[0].message}`);
            return false;
          }
        });
        if (num !== 0) {
          return false;
        }
      }
      if (num === 0) {
        return true;
      } else {
        return false;
      }
    } else {
      message.error('请维护物料');
      return false;
    }
  };

  const validateSupp = () => {
    const descriptor = {
      suppName: { type: 'string', required: true, message: '供应商名称: 必填' },
      suppCode: { type: 'string', required: true, message: '供应商编号: 必填' }
    };
    const validator = new Schema(descriptor);
    if (list.length > 0) {
      let num = 0;
      for (const item of list) {
        validator.validate(item, (errors, fields) => {
          if (errors) {
            num += 1;
            message.error(`${errors[0].message}`);
            return false;
          }
        });
        if (num !== 0) {
          return false;
        }
      }
      if (num === 0) {
        return true;
      } else {
        return false;
      }
    } else {
      message.error('邀请招标至少维护一位供应商');
      return false;
    }
  };

  function getMoment(value) {
    return moment.isMoment(value) ? value : moment(value);
  }

  function validateNum(num) {
    const reg = /^\+?[1-9][0-9]*$/;
    return reg.test(num);
  }

  const handleSave = (submitted, approveFlag) => {
    const { bidOpenTime, deadlineTime, minRegFund, minOperDays } = formData;
    const boTime = getMoment(bidOpenTime);
    const dlTime = getMoment(deadlineTime);
    formUtils.validateForm(
      [...getFormRules()],
      formData, () => {
        if(boTime <= dlTime){
          message.error(`开标时间不能早于投标截止时间`);
          return;
        }

        if (!validateNum(minRegFund)) {
          message.error(`注册资金 必须是整数`);
          return;
        }

        if (!validateNum(minOperDays)) {
          message.error(`公司运营时间 必须是整数`);
          return;
        }

        if (formData.biType === '1') {// 公开询价
          if (validateItem()) {
            dispatch({
              type: `${domain}/save`, payload: {
                submitted: (submitted !== true ? false : submitted),
                approveFlag: approveFlag,
              },
            });
          }
        } else {
          if (validateSupp()) {
            if (validateItem()) {
              dispatch({
                type: `${domain}/save`, payload: {
                  submitted: (submitted !== true ? false : submitted),
                  approveFlag: approveFlag,
                },
              });
            }
          }
        }
      });

  };

  const bidDetail = () => {
    dispatch({
      type: `${domain}/bidDetail`,
    }).then((res) => {
      if (!res) return;
      if (entType.SUPP === user.entType) {
        const { id:tenderId, bidNo, docStatus } = res;
        const { id:curTender, bidTimes } = formData; // 有效投标次数
        if(tenderId) {
          if (docStatus === '0') {
            // 仍有未投标的投标单，需要继续编辑
            dispatch({
              type: `${domain}/bidRedirect`,
              payload: {
                uri: `/source-mgmt/bid-mgmt/bids/bids/${tenderId}?mode=update`
              }
            });
          } else {
            // 已达最大次数
            message.error(resultCode.NG_MAX_TIMES);
          }
        } else {
          Modal.confirm({
            title: `有效投标次数为${bidTimes}次，您是否要进行第${bidNo}次投标？`,
            okText: '确定',
            cancelText: '取消',
            onOk: () => {
              dispatch({
                type: `${domain}/bidRedirect`,
                payload: {
                  uri: `/source-mgmt/bid-mgmt/bids/bids/${curTender}?mode=create&bidNo=${bidNo}`
                }
              });
            },
          });
        }
      } else {
        message.warn(resultCode.NG_TENDER_ONLY_SUPP);
      }
    });
  }

  const reSubmit = () => {
    const { bidOpenTime, deadlineTime } = formData;
    const bot = getMoment(bidOpenTime);
    const dlt = getMoment(deadlineTime);
    formUtils.validateForm(
      [...getFormRules()],
      formData, () => {
        if(boTime <= dlTime){
          message.error(`开标时间不能早于投标截止时间`);
          return;
        }
        if (formData.biType === '1') {// 公开询价
          if (validateItem()) {
            dispatch({
              type: `${domain}/reSubmit`
            });
          }
        } else {
          if (validateSupp()) {
            if (validateItem()) {
              dispatch({
                type: `${domain}/reSubmit`
              });
            }
          }
        }
      });
  };

  const handleCancel = () => {
    dispatch({ type: `${domain}/cancel` });
  };
  const handleApprove = () => {
    handleSave(false, 'approve');
    // dispatch({ type: `${domain}/approve` });
  };

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

  function getHepl() {
    window.open('/static/help/tender.html', '_blank', 'menubar=0, scrollbars=1, resizable=1, status=0, titlebar=0, toolbar=0, location=0');
  }

  if (remoteCfg) {

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

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

    remoteCfg.buttons.find((b) => b.id === 'notice').onClick = () => {
      // dispatch({ type: `${domain}/notice` });
    };

    const buttons = [
      {
        id: 'advice',
        placeholder: '请输入意见',
        hidden: mode !== 'approval',
        onChange: (e) => {
          dispatch({ type: `${domain}/updateState`, payload: { advice: e.target.value } });
        },
      }, {
        id: 'save',
        text: '保存',
        type: 'primary',
        hidden: saveBtnFlag ? (mode === 'view' || mode === 'approval') : true,
        onClick: () => {
          handleSave(false, null);
        },
      }, {
        id: 'submit',
        text: '提交',
        type: 'primary',
        hidden: saveBtnFlag ? (mode === 'view' || mode === 'approval') : true,
        onClick: () => {
          handleSave(true, null);
        },
      }, {
        id: 'reSubmit',
        text: '提交',
        type: 'primary',
        hidden: saveBtnFlag
          ? (!(mode === 'approval' && (user.id === formData.createUserId) && (approveStatus.REJECT === formData.approveStatus)))
          : true,
        onClick: () => {
          reSubmit();
        },
      }, {
        id: 'bid',
        text: '投标',
        type: 'primary',
        // 有按钮权限 && 查看模式 && 供应商角色 && '投标中'状态 -> 显示
        // hidden: !(bidBtnFlag && mode === 'view' && suppFlag && formData.docStatus === '2'),
        // 简化为 -> 有按钮权限 && '投标中'状态
        hidden: !(bidBtnFlag && formData.docStatus === '2'),
        onClick: () => {
          bidDetail();
        },
      },
      ...remoteCfg.buttons,
    ];
    return (
      <div style={{ height: '100%' }}>

        <Toolbar
          buttons={buttons}
          defId={suppFlag?null:formData.defId}
          handleCancel={handleCancel}
          loading={loading}
          mode={mode}
          prcId={suppFlag?null:formData.prcId}
          record={{}}
        />
        <Page dispatch={dispatch} id="tenderDetails" localCfg={config} loading={loading} remoteCfg={remoteCfg}>
            <Panel id="tenderBasic"
              title={
                <div className={styles.baseHead}>
                  <span>基本信息</span>
                  <span className={styles.baseHelp}>
                    <a href="javascript:;" onClick={ getHepl }><Icon type="question-circle-o"/>招投标须知</a>
                  </span>
                </div>
              }
            >
              <Block id="tenderBasicForm" type="form" data={formData} onFieldsChange={handleFormChange}/>
            </Panel>
            <Panel id="tenderMaterial" title="选择物料">
              <Block id="tenderMaterialList" type="table" data={mlist}
                     extraInfo={{ suppFlag: suppFlag, suppList: list }}
                     {...materialTableProps}/>
            </Panel>
            <Panel id="tenderTeam" title="选择评标小组" hidden={suppFlag}>
              <Block id="tenderTeamForm" type="form" data={formData} onFieldsChange={handleFormChange}
              extraInfo={{c3code: (mlist && mlist.length) ? mlist[0].c3code: null}}/>
            </Panel>
            <Panel id="tenderSupplier" title="选择供应商" hidden={suppFlag || formData.biType === '1'}>
              <Block
                id="tenderSupplierList"
                type="table"
                data={list}
                extraInfo={{
                  suppCenterId: formData ? formData.suppCenterId : null,
                  itemCodes: mlist ? mlist.filter(i=>i.itemCode && i.itemCode.trim()!=='').map(i=>i.itemCode) : []
                }}
                {...supplierTableProps}
              />
            </Panel>
          </Page>
        {/*招标文件上传=============*/}
        {attachRepo && (( mode === 'create' ?
        <Card id="tenderAttch" title="招标文件">
            <UploadEL
              api={`/api/source-mgmt/bid-mgmt/tenders/tenders/sfs/token?clsPath=${attachRepo}`}
              dataKey={null}
              listTypes={'text'}
            />
        </Card> :
        <Card id="tenderAttch" title="招标文件">
            {formData.id &&
            <UploadEL disabled={viewFlag}
              api={`/api/source-mgmt/bid-mgmt/tenders/tenders/sfs/token?clsPath=${attachRepo}&dataKey=${formData.id}`}
              dataKey={formData.id}
              listTypes={'text'}
            />
            }
        </Card>
        ))}
        {/*招标文件上传=============*/}
      </div>);
  } else {
    return <Loader fullScreen={false} spinning={loading.effects[`${domain}/query`]}/>;
  }
};

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