import { Block, Page, Panel, Toolbar } from '@bizComponents';
import { Loader, UploadEL, EditableDataTable } from '@components';
import { enums, formUtils } from '@utils';
import { Card, DatePicker, Input, message, Icon, Modal } from 'antd';
import Schema from 'async-validator';
import { connect } from 'dva';

import React from 'react';
import config from './inquiryDetailCfg';
import QuoteModal from './quoteModal';
import styles from './styles.less';

import { ExcelImport } from '../../components';
import {switchBargain} from "../../../services/source/inquiry";

const { confirm } = Modal;
const { peStatus, approveStatus } = enums;

const Detail = ({ inquiryDetails, dispatch, loading }) => {
  const { user, remoteCfg, mode, formData, list, mlist, quoteData, editMaterialFlag, abandonBargainBtnFlag, reBargainBtnFlag,
    readOnly, suppFlag, saveBtnFlag, priceBtnFlag, yjconfirmBtnFlag, attachRepo, taxList, suppId, quoteModalVisible,
    showUploadModal, collectData, adjustBargainDeadline } = inquiryDetails;
  const domain = 'inquiryDetails';
  const domainCN = '询价单详情';
  let viewFlag = true;
  const width = '20%';
  let notQuoteNum;
  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%',
    },
    domain,
    dispatch,
    loading,
    // dataSource: list,
    showAdd: false, // !viewFlag,
    showDelete: false,
    showCopy: false,
    size: 'small',
    enableSelection: false,
    // footer: null,
    // readOnly,
    // columns: [],
  };

  // 物料列
  const materialTableProps = {
    rowKey: 'id',
    scroll: {
      x: 3120,
      y: 500,
    },
    domain,
    dispatch,
    loading,
    // dataSource: mlist,
    showAdd: editMaterialFlag,
    showDelete: editMaterialFlag,
    showCopy: false,
    size: 'small',
    rowSelection: {
      columnWidth: 20,
      fixed: true,
    },
    // enableSelection: viewFlag,
    // readOnly,
    // columns: [],
    // buttons:[{
    //   key: 'viewResult',
    //   type: 'primary',
    //   name: '查看比价结果',
    //   requiredSelected: viewButton,
    //   cb: (selectedKeys) => {
    //     dispatch({
    //       type:`${domain}/getSingle`,
    //       payload:{ mode:'create'}
    //     });
    //   },
    // }]
    buttons: [{
      key: 'upload',
      type: 'primary',
      hidden: !editMaterialFlag,
      requiredSelected: 0,
      name: 'Excel导入',
      cb: (selectedKeys) => {
        dispatch({
          type: `${domain}/updateState`,
          payload: { showUploadModal: true }
        });
      },
    }]
  };

  const showQuoteConfirmModal =  () => {
    confirm({
      title: '确认报价',
      content: notQuoteNum === 0 ? null : `还有${notQuoteNum}条物料未报价, 是否确定报价?`,
      okText: '确认',
      onOk() {
        // message.success("报价成功");
        dispatch({
          type: `${domain}/save`, payload: {
            submitted: false,
          },
        });
      },
      cancelText: '取消',
      onCancel() {
      },
    });
  };

  const handleUpload = (data) => {
    dispatch({
      type: `${domain}/handleUpload`,
      payload: { data }
    });
  }

  const uploadModal = {
    domain,
    dispatch,
    autoQuery: false,
    showModal: showUploadModal,
    callback: handleUpload,
    dataSource: [{
      aim: 'inquiry-details',
      name: '询价单物料明细',
      temp: 'Inquiry_Details',
      tempName: '物料导入模板',
      params: {
        suppId: suppId
      }
    }],
  };

  const collectTableProps = {
    enableSelection: false,
    scroll: { x: '100%' },
    domain,
    dispatch,
    loading,
    dataSource: collectData,
    showAdd: false,
    showDelete: false,
    showCopy: false,
    size: 'small',
    readOnly,
    columns: [
      {
        title: '物料品项数',
        dataIndex: 'itemCount',
        width: '25%',
      },
      {
        title: '物料数量',
        dataIndex: 'itemNumber',
        width: '25%',
      },
      {
        title: '报价总金额',
        dataIndex: 'quoteAmt',
        width: '25%',
      },
      {
        title: '议价总金额',
        dataIndex: 'bargainAmt',
        width: '25%',
      },
    ],
  }

  const hideQuoteModal = () => {
    dispatch({ type: `${domain}/hideQuoteModal` });
  }

  const modalProps = {
    record: formData,
    visible: quoteModalVisible,
    onCancel: hideQuoteModal,
  };

  const handleFormChange = (field) => {
    const key = Object.keys(field)[0];
    if ('deadlineHour' === key && 0 === field[key]) return;

    dispatch({
      type: `${domain}/updateForm`,
      payload: {
        key,
        value: field[key],
      },
    });
    if (key === 'recCompany') {
      dispatch({ type: `${domain}/updateOu`, payload: field[key] });
    } else if (key === 'quoteType') {
      dispatch({ type: `${domain}/updateQuoteType`, payload: field[key] });
    }

  };

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

    dispatch({
      type: `${domain}/updateQuoteForm`,
      payload: {
        key,
        value: field[key],
      },
    });
  };
  const getFormRules = () => {
    const remoteData = remoteCfg.panels.find((x) => {
      return x.panelId === 'inquiryBasic';
    }).blocks.find((y) => {
      return y.blockId === 'inquiryBasicForm';
    }).fields;
    const newFormData = config(formData, mode, dispatch, loading, {}).inquiryBasicForm.slice();
    newFormData.forEach((item) => {
      const remoteItem = remoteData.find((z) => {
        return z.fieldId === item.dataIndex;
      });
      if (remoteItem && remoteItem.required === 1) {
        item.options.rules[0].required = true;
      }
    });
    return newFormData;
  };
  const getQuoteRules = () => {
    const remoteData = remoteCfg.panels.find((x) => {
      return x.panelId === 'inquiryQuote';
    }).blocks.find((y) => {
      return y.blockId === 'inquiryQuoteForm';
    }).fields;
    const newQuoteData = config(formData, mode, dispatch, loading, {}).inquiryQuoteForm.slice();
    newQuoteData.forEach((item) => {
      const remoteItem = remoteData.find((z) => {
        return z.fieldId === item.dataIndex;
      });
      if (remoteItem.required === 1) {
        item.options.rules[0].required = true;
      }
    });
    return newQuoteData;
  };

  const validateItem = () => {
    if (mlist.length > 0) {
      let quoteNum = 0; // 报价数量
      for (const item of mlist) {
        if (suppFlag) {
          if (item.taxPrice != null) {
            quoteNum++;
          }
        } else {
          if (item.itemDesc == null) {
            message.error(`物料名称：必选`);
            return false;
          } else if (item.itemId == null) {
            message.error(`物料：必选`);
            return false;
          } else if (item.taxRate == null) {
            message.error(`物料:${item.itemDesc} 没有选择税率`);
            return false;
          } else if (item.estimatedNum == null) {
            message.error(`物料:${item.itemDesc} 没有填写当期预估用量`);
            return false;
          } else if (item.estimatedNum <= 0) {
            message.error(`物料:${item.itemDesc} 填写的当期预估用量必须大于0`);
            return false;
          }
        }
      }
      if (suppFlag) {
        notQuoteNum = mlist.length - quoteNum;
        if (quoteNum == 0) {
          message.error('至少填写一个物料的"含税报价"进行报价, 不填写"含税报价"被视为不报价');
          return false;
        }
        // dispatch({
        //   type: `${domain}/updateState`,
        //   payload: {
        //     notQuoteNum: mlist.length - quoteNum,
        //   },
        // });
      }
      return true;
    } else {
      message.error('请维护物料');
      return false;
    }
    // let itemDescriptor;
    // if (suppFlag) {
    //   itemDescriptor = {
    //     // itemDesc: { type: 'string', required: true, message: '物料名称：必填' },
    //     // itemId: { type: 'number', required: true, message: '物料：必选' },
    //     //fromDate: { required: true, message: '价格生效日：未设置品类询价时间' },
    //     //toDate: { type: 'string', required: true, message: '价格失效日：未设置品类询价时间' },
    //     // minNum: { type: 'number', required: true, message: '起订量：必填' },
    //     taxPrice: { type: 'number', required: true, message: '含税报价(元)：必填' },
    //     // taxRate: { required: true, message: '税率：必填' },
    //     // netPrice: { required: true, message: '未税报价(元)：必填' },
    //     // netAmt: { required: true, message: '未税金额(元)：必填' },
    //     // amt: { required: true, message: '含税金额(元)：必填' },
    //     // taxAmt: { required: true, message: '税额(元)：必填' },
    //     // proportion: {type: "number", required: true,  message: '分配比例：必填，数字'},
    //     // maxProvideNum: { type: 'number', required: true, message: '最高可供应量：必填' },
    //     // orderPeriod: { type: 'number', required: true, message: '订货或生产周期(天)：必填' },
    //     // deliveryPeriod: { type: 'number', required: true, message: '物流配送时间(天)：必填' },
    //     // remark: { type: 'string', max: 200, message: '备注：不能超过200字' },
    //   };
    // } else {
    //   itemDescriptor = {
    //     itemDesc: { type: 'string', required: true, message: '物料名称：必填' },
    //     itemId: { type: 'number', required: true, message: '物料：必选' },
    //     taxRate: { required: true, message: '税率：必选' },
    //     //fromDate: { required: true, message: '价格生效日：未设置品类询价时间' },
    //     //toDate: { type: 'string', required: true, message: '价格失效日：未设置品类询价时间' },
    //     estimatedNum: { type: 'number', required: true, message: '当期预估用量：必填' },
    //     // estimatedAmt: { type: 'number', required: true, message: '预估采购额(元)：必填' },
    //   };
    // }
    // const itemValidator = new Schema(itemDescriptor);
    // if (mlist.length > 0) {
    //   let errorNum = 0; //产生错误的数量
    //   let quoteNum = 0; //报价数量
    //   console.log("mlist",mlist);
    //   for (const item of mlist) {
    //     // console.log('item==>',item)
    //     if (suppFlag) {
    //       // 1.由于页面可能出现税率进行了选择，但是无法取消的情况，所以是否报价只取决于含税报价是否进行了填写
    //       // 2.只要含税报价没有填，即使税率进行了填写，都认为供应商不对此物料报价，不需要做数据校验，否则需要进行数据校验
    //       if (item.taxPrice) {
    //         quoteNum += 1;
    //         itemValidator.validate(item, (errors, fields) => {
    //           if (errors) {
    //             errorNum += 1;
    //             message.error(`${errors[0].message}`);
    //             return false;
    //           }
    //         });
    //       }
    //     } else {
    //       // console.log('item=',item)
    //       if (item.estimatedNum == 0) {
    //         message.error('当期预估用量必须大于0');
    //         return false;
    //       }
    //       itemValidator.validate(item, (errors, fields) => {
    //         if (errors) {
    //           errorNum += 1;
    //           message.error(`${errors[0].message}`);
    //           return false;
    //         }
    //       });
    //     }
    //   }
    //   // 如果一个报价都没有则报错
    //   if (suppFlag) {
    //     if (quoteNum === 0) {
    //       message.error('至少填写一个物料的"含税报价"进行报价, 不填写"含税报价"被视为不报价');
    //       return false;
    //     }
    //   }
    //   return errorNum === 0;
    // } 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;
    }
  };
  const handlePrice = () => {
    if (peStatus.DELETE === formData.docStatus) {
      message.warn('询价单已作废，没有报价明细');
    } else {
      // dispatch({
      //   type: `${domain}/viewQuote`,
      // });
      dispatch({ type: `${domain}/showQuoteModal` });
    }
  };

  const handleYjconfirm = () => {
    dispatch({ type: `${domain}/yjconfirm` });
  };

  const handleSwitchBargain = (action) => {
    dispatch({
      type: `${domain}/switchBargain`,
      payload: {
        action: action,
      },
    });
  };

  const handleSave = (submitted) => {
    if (suppFlag) {// 供应商，不会发起流程，只填写选择物料后半部分和报价说明
      formUtils.validateForm(
        [...getQuoteRules()],
        quoteData, () => {
          if (validateItem()) {
            showQuoteConfirmModal();
            // dispatch({
            //   type: `${domain}/save`, payload: {
            //     submitted: false,
            //   },
            // });
          }
        });
    } else {
      formUtils.validateForm(
        [...getFormRules()],
        formData, () => {
          if (formData.quoteType === '01') {// 公开询价
            if (validateItem()) {
              dispatch({
                type: `${domain}/save`, payload: {
                  submitted: (submitted !== true ? false : submitted),
                },
              });
            }
          } else {
            if (validateSupp()) {
              if (validateItem()) {
                dispatch({
                  type: `${domain}/save`, payload: {
                    submitted: (submitted !== true ? false : submitted),
                  },
                });
              }
            }
          }
        });
    }

  };
  const reSubmit = () => {
    formUtils.validateForm(
      [...getFormRules()],
      formData, () => {
        if (formData.quoteType === '01') {// 公开询价
          if (validateItem()) {
            dispatch({
              type: `${domain}/reSubmit`
            });
          }
        } else {
          if (validateSupp()) {
            if (validateItem()) {
              dispatch({
                type: `${domain}/reSubmit`
              });
            }
          }
        }
      });
  };

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

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

  function getHepl() {
    window.open('/static/help/inquiry.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 ? (((!suppFlag) && (mode === 'view' || mode === 'approval')) || peStatus.FINISH === formData.docStatus || mode === 'quote' || mode === 'yjAdjust' || mode === 'yjconfirm' || mode === 'quoteview') : true,
        onClick: () => {
          // console.log(formData.docStatus);
          handleSave(false);
        },
      }, {
        id: 'save',
        text: '保存', // 议价保存/调整议价保存
        type: 'primary',
        hidden: mode === 'quote' || mode === 'yjAdjust' ? formData.docStatus === peStatus.NO_ACCEPT : true,
        onClick: () => {
          // console.log(formData.docStatus);
          handleSave(false);
        },
      }, {
        id: 'submit',
        text: '提交',
        type: 'primary',
        hidden: saveBtnFlag ? (mode === 'view' || mode === 'approval' || mode === 'quote' || mode === 'quoteview' || mode === 'yjconfirm') : true,
        onClick: () => {
          handleSave(true);
        },
      }, {
        id: 'reSubmit',
        text: '提交',
        type: 'primary',
        hidden: saveBtnFlag
          ? (mode === 'quote' || mode === 'quoteview' || mode === 'yjconfirm' || !(mode === 'approval' && (user.user.id === formData.createUserId) && (approveStatus.REJECT === formData.approveStatus)))
          : true,
        onClick: () => {
          reSubmit();
        },
      }, {
        //   id: 'price',
        //   text: '查看报价明细',
        //   type: 'primary',
        //   hidden: priceBtnFlag ? (suppFlag || mode === 'create' || mode === 'update' || mode === 'quote' || peStatus.DOING === formData.docStatus || peStatus.WAITING === formData.docStatus) : true,
        //   onClick: () => {
        //     handlePrice();
        //   },
        // }, {
        id: 'yjconfirm',
        text: '确认议价',
        type: 'primary',
        hidden: mode === 'yjconfirm' ? !yjconfirmBtnFlag : true,
        onClick: () => {
          handleYjconfirm();
        },
      }, {
        id: 'abandonBargain',
        text: '放弃议价',
        type: 'primary',
        hidden: mode === 'quote' ? !abandonBargainBtnFlag : true,
        onClick: () => {
          handleSwitchBargain("abandon");
        },
      }, {
        id: 'reBargain',
        text: '重新议价',
        type: 'primary',
        hidden: mode === 'quote' ? !reBargainBtnFlag : true,
        onClick: () => {
          handleSwitchBargain("reopen");
        },
      },
      ...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={formData}
        />
        {
          (formData.quoteType !== '01') &&
          (<Page dispatch={dispatch} id="inquiryDetails" localCfg={config} loading={loading} remoteCfg={remoteCfg}>
            <Panel id="inquiryBasic"
              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="inquiryBasicForm" type="form" data={formData} onFieldsChange={handleFormChange} />
            </Panel>
            <Panel id="inquirySupplier" title="选择供应商">
              <Block
                id="inquirySupplierList"
                type="table"
                data={list}
                extraInfo={{ suppCenterId: formData ? formData.suppCenterId : null }}
                {...supplierTableProps}
              />
            </Panel>

            <Card title="汇总列表" loading={loading.effects[`${domain}/query`]} id="collection">
              <EditableDataTable {...collectTableProps} />
            </Card>

            <Panel id="inquiryMaterial" title="选择物料">
              <Block
                id="inquiryMaterialList"
                type="table"
                data={mlist}
                extraInfo={{ suppCenterId: formData ? formData.suppCenterId : null, taxList: taxList, suppId: suppId, editMaterialFlag: editMaterialFlag }}
                {...materialTableProps} />
            </Panel>
            <Panel id="inquiryQuote" title="报价说明" isOpened={suppFlag}>
              <Block id="inquiryQuoteForm" type="form" data={quoteData} onFieldsChange={handleQuoteFormChange} />
            </Panel>
          </Page>)
        }
        {
          (formData.quoteType === '01') &&
          (<Page dispatch={dispatch} loading={loading} localCfg={config} remoteCfg={remoteCfg} id="inquiryDetails">
            <Panel id="inquiryBasic"
              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="inquiryBasicForm" type="form" data={formData} onFieldsChange={handleFormChange} />
            </Panel>

            <Card title="汇总列表" loading={loading.effects[`${domain}/query`]} id="collection">
              <EditableDataTable {...collectTableProps} />
            </Card>

            <Panel id="inquiryMaterial" title="选择物料">
              <Block id="inquiryMaterialList"
                type="table"
                data={mlist}
                extraInfo={{ suppCenterId: formData ? formData.suppCenterId : null, taxList: taxList }}
                {...materialTableProps} />
            </Panel>
            <Panel id="inquiryQuote" title="报价说明" isOpened={suppFlag}>
              <Block id="inquiryQuoteForm" type="form" data={quoteData} onFieldsChange={handleQuoteFormChange} />
            </Panel>
          </Page>)
        }
        {/*报价附件上传=============*/}
        {attachRepo && (
          (quoteData && quoteData.id)
            ? (<Card id="quoteAttch" title="报价附件">
              <UploadEL disabled={peStatus.FINISH === formData.docStatus}
                api={`/api/source-mgmt/qo/iqo/sfs/token?clsPath=${attachRepo}&dataKey=${quoteData.id}`}
                dataKey={quoteData.id}
                listTypes={'text'}
              />
            </Card>)
            : (<Card id="quoteAttch" title="报价附件">
              <UploadEL disabled={peStatus.FINISH === formData.docStatus}
                api={`/api/source-mgmt/qo/iqo/sfs/token?clsPath=${attachRepo}`}
                dataKey={null}
                listTypes={'text'}
              />
            </Card>)
        )
        }
        {/*报价附件上传=============*/}
        <Card title="询价说明" id="inquiryDesc">
          <p>1、质量要求：报价供应商确保供应产品符合我司产品验收标准及合同约定的产品质量要求；</p>
          <p>2、供应量要求：报价供应商应满足我司预估采购量（±20%）范围内的采购需求，确保按时按量向我司供应订购产品；</p>
          <p>3、我司有权将根据供应商首次报价优劣排序分配采购量；</p>
          <p>4、供应商务必于在报价截止时间前完成报价，若延迟报价或报价不完整的，则视为弃权处理；</p>
          <p>5、本询价说明与供应合同具有法律效力，供应商参与报价即视为其阅读并同意本询价说明。</p>
        </Card>

        <QuoteModal {...modalProps} />


        {showUploadModal && <ExcelImport {...uploadModal} />}

      </div>);
  } else {
    return <Loader fullScreen={false} spinning={loading.effects[`${domain}/query`]} />;
  }
};

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