import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Icon, Select, Tabs, Radio, DatePicker, message, Upload, InputNumber, Checkbox } from 'antd';
import { FormattedMessage } from 'umi-plugin-react/locale';
import moment from 'moment';
import router from 'umi/router';
import styles from '../../../../style/GoodsList.less';
import XForm, { FieldTypes } from '../../../../../components/XForm';
import apis from '../../../../../services/apis';
import BuildingSelect from './BuildSelect/BuildSelect';
import request from '../../../../../utils/request';
import SalesBatchHelpDoc from './SalesBatchHelpDoc';
import MiniQRCode from '@/components/MiniQRCode';
import SalesBatch from '../../../preSelect/edit/components/SalesBatch/SalesBatch';
import SalesBatchSelect from '../../../../../components/HouseSelect/SalesBatchSelect';
import Wangedit from '../../../../../components/Wangedit/Wangedit'

const { MonthPicker, RangePicker, WeekPicker } = DatePicker;
const { TextArea } = Input;

const Base = props => {
  const raiseId = props.raiseId.raiseId
  const salesBatchId = props.salesBatchId
  const [saleBatchData, setSaleBatchData] = useState({})
  const [showHelp, setShowHelp] = useState(false)
  const [houseLockingType, setHouseLockingType] = useState('')
  const [preSelectFlag, setPreSelectFlag] = useState(false)
  const [invite, setInvite] = useState()
  const [isShowInviteTel, setIsShowInviteTel] = useState()

  if (raiseId) {
    useEffect(() => {
      getSaleBatchData(raiseId);
      onChangeValue(salesBatchId);
    }, [])

    // 查询列表
    const getSaleBatchData = (raiseId) => {
      request({ ...apis.house.taRaiseById, urlData: { id: raiseId } }).then((data) => {
        console.log(data)
        setSaleBatchData(data)

        if (data != null && data.invite == 1) {
          setIsShowInviteTel("block")
        } else {
          setIsShowInviteTel("none")
        }
      })
    }
  }

  const cancelPage = () => {
    router.push({
      pathname: '/house/raise/list',
    });
  }

  function onChangeValue(e) {
    request({ ...apis.house.checkHavingRecord, urlData: { id: e } }).then((data) => {
      setPreSelectFlag(data.havingRecord)
      console.log(preSelectFlag)
    })

  }

  function changeHouseLockingType(e) {
    props.form.resetFields("payType");
    if (e === 'auto') {
      setHouseLockingType('onLine');
    } else {
      setHouseLockingType('');
    }
  }

  function toDecimal2(x) {
    var f = parseFloat(x);
    if (isNaN(f)) {
      return false;
    }
    var f = Math.round(x * 100) / 100;
    var s = f.toString();
    var rs = s.indexOf('.');
    if (rs < 0) {
      rs = s.length;
      s += '.';
    }
    while (s.length <= rs + 2) {
      s += '0';
    }
    console.log(s)
    return s;
  }
  function regFenToYuan(fen) {
    var num = fen;
    num = fen * 0.01;
    num += '';
    var reg = num.indexOf('.') > -1 ? /(\d{1,3})(?=(?:\d{3})+\.)/g : /(\d{1,3})(?=(?:\d{3})+$)/g;
    num = num.replace(reg, '$1');
    console.log(num, 'yuan')
    num = toDecimal2(num)
    return num
  }

  function handleSubmit(e) {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        console.log(values)
        if (values.payType == 'onLine' && (values.payDescriptionOnline == '' || values.payDescriptionOnline == null)) {
          message.info("请填写线上缴费说明");
          return;
        }
        if (values.payType == 'offLine' && (values.payDescriptionOffline == '' || values.payDescriptionOffline == null)) {
          message.info("请填写线下缴费说明");
          return;
        }
        if ((values.payType == 'onLine' && (values.payDescriptionOnline == '' || values.payDescriptionOnline == null)) ||
          (values.payType == 'offLine' && (values.payDescriptionOffline == '' || values.payDescriptionOffline == null))) {
          message.info("请填写缴费说明");
          return;
        }

        let { liveTime, ...submitValue } = values
        if (values.raiseStartTime > values.raiseEndTime) {
          message.info("认筹结束时间大于认筹开始时间")
          return;
        }
        values.raiseStartTime = moment(values.raiseStartTime).format('YYYY-MM-DD HH:mm:ss')
        values.raiseEndTime = moment(values.raiseEndTime).format('YYYY-MM-DD HH:mm:ss')
        values.payType = values.payType.toString();
        values.raisePrice = values.raisePrice * 100;
        request({ ...apis.house.updateRaise, urlData: { id: raiseId }, data: { ...values }, }).then((data) => {
          message.info("保存成功")
        }).catch((err) => {
          message.info(err.msg || err.message)
        })
      }
    });
  }

  const changeInvite = e => {
    if (e.target.value == 1) {
      setInvite(1)
      setIsShowInviteTel("block")
    } else {
      setInvite(0)
      setIsShowInviteTel("none")
    }
  }

  const { getFieldDecorator } = props.form;

  return (
    <>
      <Form labelCol={{ span: 7 }} wrapperCol={{ span: 12 }} onSubmit={handleSubmit}>
        <Form.Item label="销售楼盘">
          {getFieldDecorator('buildingId', {
            initialValue: saleBatchData.buildingId,
            rules: [{ required: true, message: ' 请输入销售楼盘' }],
          })(<BuildingSelect />)}
        </Form.Item>
        <Form.Item label="销售批次">
          {getFieldDecorator('salesBatchId', {
            rules: [{ required: true, message: ' 请输入销售批次' }], onChange: onChangeValue
            , initialValue: saleBatchData.salesBatchId
          })
            (<SalesBatch type='false' />)}
        </Form.Item>
        <Form.Item label="备注">
          {getFieldDecorator('remark', { initialValue: saleBatchData.remark })(<Input disabled />)}
        </Form.Item>
        <Form.Item label="发布状态">
          {getFieldDecorator('status', {
            rules: [{ required: true, message: ' 请输入销售批次' }], onChange: onChangeValue
            , initialValue: saleBatchData.status == 1 ? '1' : '0'
          })(<Select placeholder="发布状态" style={{ width: '300px' }} disabled>
            <Option value="0">否</Option>
            <Option value="1">是</Option>
          </Select>)}
        </Form.Item>
        <Form.Item label="认筹开始时间">
          {getFieldDecorator('raiseStartTime', {
            initialValue: saleBatchData.raiseStartTime ? moment(saleBatchData.raiseStartTime, 'YYYY-MM-DD HH:mm:ss') : null,
            rules: [
              {
                required: true,
                message: '请选择认筹开始时间',
              },
            ],
          })(<DatePicker showTime={{ format: 'HH:mm:ss' }} format="YYYY-MM-DD HH:mm:ss" />)}
        </Form.Item>
        <Form.Item label="认筹结束时间">
          {getFieldDecorator('raiseEndTime', {
            initialValue: saleBatchData.raiseEndTime ? moment(saleBatchData.raiseEndTime, 'YYYY-MM-DD HH:mm:ss') : null,
            rules: [
              {
                required: true,
                message: '请选择认筹结束时间',
              },
            ],
          })(<DatePicker showTime={{ format: 'HH:mm:ss' }} format="YYYY-MM-DD HH:mm:ss" />)}
        </Form.Item>
        <Form.Item label="锁房方式" help="自动锁房仅适用于线上支付认筹且每次只能认筹一套房源且认筹后其他人无法认筹此房源。其他情况请使用手动锁房。">
          {getFieldDecorator('houseLockingType', {
            initialValue: saleBatchData.houseLockingType,
            rules: [{ required: true, message: '请选择锁房方式' }], onChange: changeHouseLockingType
          })(<Select placeholder="发布状态" style={{ width: '300px' }} disabled>
            <Option value="auto">自动锁房</Option>
            <Option value="manual">手动锁房</Option>
          </Select>)}
        </Form.Item>
        <Form.Item style={{ marginTop: '20px' }} label="认筹金额" help="最高50000元(需要微信商户号配置的行业为房地产行业：房地产开发，物业，房产中介。若微信商户号配置为其他行业则为3000元若不确定请联系平台相关运营人员。">
          {getFieldDecorator('raisePrice', {
            initialValue: regFenToYuan(saleBatchData.raisePrice),
            rules: [{ required: true, message: '请输入认筹金额' }],
          })(<InputNumber max={50000} min={0.01} step={0.01} placeholder="认筹缴费金额" style={{ width: '200px' }} />)}<span>元</span>
        </Form.Item>
        <Form.Item style={{ marginTop: '20px' }} label="认筹需预选" help="设置是否需要客户之前预选了房源才能认筹。">
          {getFieldDecorator('needPreselection', {
            initialValue: saleBatchData.needPreselection === false ? 'false' : 'true',
            rules: [{ required: true, message: '请选择认筹需预选' }],
          })(<Select placeholder="预选方式" style={{ width: '300px' }} disabled={preSelectFlag ? false : true}>
            <Option value="false">否</Option>
            <Option value="true">是</Option>
          </Select>)}
        </Form.Item>
        <Form.Item style={{ marginTop: '20px' }} label="缴费方式" help="锁房方式为自动锁房，缴费方式仅支持线上缴费。锁房方式为手动锁房，缴费方式可多选，线上缴费使用微信支付，线下缴费客户可提交后去线下缴费。">
          {getFieldDecorator('payType', {
            rules: [{ required: true, message: '请选择缴费方式' }],
            initialValue: saleBatchData.payType === 'onLine' ? 'onLine' : saleBatchData.payType === 'offLine' ? "offLine" : ['offLine', 'onLine'],
          })(
            <Checkbox.Group style={{ width: '100%' }}>
              <Checkbox value="onLine" disabled={houseLockingType === 'onLine' || (saleBatchData.houseLockingType === 'auto') ? true : false}>线上缴费</Checkbox>
              <Checkbox value="offLine" disabled={houseLockingType === 'onLine' || (saleBatchData.houseLockingType === 'auto') ? true : false}>
                线下缴费
            </Checkbox>
            </Checkbox.Group>,
          )}
        </Form.Item>
        <Form.Item style={{ marginTop: '20px' }} label="线上缴费说明">
          {getFieldDecorator('payDescriptionOnline', { initialValue: saleBatchData.payDescriptionOnline })(<TextArea placeholder="向客户说明线上缴费相关业务需求" style={{ height: '300px' }}></TextArea>)}
        </Form.Item>
        <Form.Item label="线下缴费说明">
          {getFieldDecorator('payDescriptionOffline', { initialValue: saleBatchData.payDescriptionOffline })(<TextArea placeholder="填写线下缴费时间地点要求" style={{ height: '300px' }}></TextArea>)}
        </Form.Item>
        <Form.Item label="认筹单注意事项">
          {getFieldDecorator('raisePrecautions', { initialValue: saleBatchData.raisePrecautions })(<Input maxLength={100} placeholder="客户提交认筹单后的注意事项" />)}
        </Form.Item>
        <Form.Item label="选房协议" help="若想在协议中自动引用客户信息生成带客户信息的协议，请在选房协议中按如下格式引用:
                                         ${name}其中name代表客户姓名,
                                         ${idcard}其中idcard代表身份证号,
                                         ${phone}其中phone代表手号,
                                         ${date}其中date代表日期（如2020/03/10）,
                                         举例，若想在协议中“乙方：”后显示当前客户姓名，在“乙方：”后输入${name}即可。
                                         注意，在提交认筹单后在认筹单详情中查看协议才能看到这些引用的具体信息，在认筹过程中，因阅读协议在填写个人信息之前，这些信息会为空白。">
          {getFieldDecorator('payProtocol', {
            rules: [{ required: true, message: '请输入选房协议' }],
            initialValue: saleBatchData.payProtocol
          })(<Wangedit />)}
        </Form.Item>

        <Form.Item label="是否为邀请制" help="若为邀请制，则需要填写哪些手机号的用户可以看到认筹，不在邀请范围内的用户无法认筹，若不为邀请制，则认筹发布后，小程序全部用户都可以进入认筹。">
          {getFieldDecorator('invite', {
            rules: [{ required: true, message: '请选择是否为邀请制' }],
            initialValue: saleBatchData.invite === null ? 0: saleBatchData.invite
          })(<Radio.Group onChange={changeInvite}>
            <Radio value={1}>是</Radio>
            <Radio value={0}>否</Radio>
          </Radio.Group>)}
        </Form.Item>

        <Form.Item label="被邀请人清单" style={{ display: isShowInviteTel }}>
          {getFieldDecorator('inviteTel', { initialValue: saleBatchData.inviteTel })(<TextArea placeholder="填写被邀请人手机号，每个手机号换行即可，建议在txt文本中编辑好后复制粘贴进来" style={{ height: '300px' }}></TextArea>)}
        </Form.Item>

        <Form.Item label="扫码查看房源列表">
          {getFieldDecorator('qrCode', {
            rules: [{ required: true, message: '请输入选房协议' }],
            initialValue: saleBatchData.payProtocol
          })(<MiniQRCode targetId={saleBatchData.salesBatchId} page="onlineSelling/pages/houseList/index" />)}
        </Form.Item>

        <Form.Item wrapperCol={{ span: 15, offset: 7 }}>
          <Button type="primary" htmlType="submit" style={{ marginRight: '20px' }}>
            提交
          </Button>
          <Button onClick={() => router.go(-1)}>
            取消
          </Button>
        </Form.Item>
      </Form>
    </>
  )
}

const WrappedBase = Form.create({ name: 'Base' })(Base);

export default WrappedBase
