import React, { useState, useEffect } from 'react';
import { Form, Input, Button, Icon, Select, message, Table, Divider, Tag, Pagination, Modal, DatePicker, InputNumber, Checkbox, Radio, Row, Col } from 'antd';
import { FormattedMessage } from 'umi-plugin-react/locale';
import XForm, { FieldTypes } from '../../../../components/XForm';
import router from 'umi/router';
import moment from 'moment';
import styles from '../../../style/GoodsList.less';
import SelectCity from '../../../../components/SelectButton/CitySelect'
// import BuildSelect from '../../../../components/SelectButton/BuildSelect'
import BuildSelect from '../edit/components/BuildSelect/BuildSelect';
import ImageUpload from '../../../../components/XForm/ImageUpload'
import apis from '../../../../services/apis';
import request from '../../../../utils/request';
import AuthButton from '@/components/AuthButton';
import SaleBatchHelpDoc from '../edit/components/SalesBatchHelpDoc';
import SalesBatchSelect from '../../../../components/HouseSelect/SalesBatchSelect';
import Wangedit from '../../../../components/Wangedit/Wangedit'
import TextArea from 'antd/lib/input/TextArea';
import SalesBatch from '../../preSelect/edit/components/SalesBatch/SalesBatch';

const { Option } = Select;
const { MonthPicker, RangePicker, WeekPicker } = DatePicker;




const header = props => {
  const { salesBatchId } = props.location.query
  console.log(salesBatchId)
  const [saleBatchData, setSaleBatchData] = useState({})
  const [showHelp, setShowHelp] = useState(false)
  const [houseLockingType, setHouseLockingType] = useState('')
  const [preSelectFlag, setPreSelectFlag] = useState(false)
  const [isInvite, setInvite] = useState()
  const [isShowInviteTel,setIsShowInviteTel] =useState('none')

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

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

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

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

  }

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

  function handleSubmit(e) {
    e.preventDefault();
    props.form.validateFields((err, values) => {
      if (!err) {
        console.log(values, 'valuesvaluesvalues')
        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;
        }
        submitValue.raiseStartTime = moment(submitValue.raiseStartTime).format('YYYY-MM-DD HH:mm:ss')
        submitValue.raiseEndTime = moment(submitValue.raiseEndTime).format('YYYY-MM-DD HH:mm:ss')
        submitValue.payType = values.payType.toString();
        submitValue.raisePrice = submitValue.raisePrice * 100;
        request({ ...apis.house.addRaise, data: { ...submitValue }, }).then((data) => {
          message.info("保存成功")
          router.push({
            pathname: '/house/raise/list',
          });
        }).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 inviteOptions = {
    value: 0
  };

  const { getFieldDecorator } = props.form;

  return (
    <>
      <Form labelCol={{ span: 7 }} wrapperCol={{ span: 12 }} onSubmit={handleSubmit}>
        <Form.Item label="销售楼盘">
          {getFieldDecorator('buildingId', {
            rules: [{ required: true, message: ' 请输入销售楼盘' }],
          })(<BuildSelect type='false' salesBatchId={props.form.getFieldValue('salesBatchId')} />)}
        </Form.Item>
        <Form.Item label="销售批次" help="销售批次请在房源管理中新增">
          {getFieldDecorator('salesBatchId', {
            rules: [{ required: true, message: ' 请输入销售批次' }], onChange: onChangeValue
          })(<SalesBatch type='true' buildingId={props.form.getFieldValue('buildingId')} />)}
        </Form.Item>
        <Form.Item style={{ marginTop: '20px' }} label="认筹开始时间">
          {getFieldDecorator('raiseStartTime', {
            rules: [
              {
                required: true,
                message: '请选择认筹开始时间',
              },
            ],
          })(<DatePicker showTime={{ format: 'HH:mm:ss' }} format="YYYY-MM-DD HH:mm:ss" />)}
        </Form.Item>
        <Form.Item label="认筹结束时间">
          {getFieldDecorator('raiseEndTime', {
            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', {
            rules: [{ required: true, message: '请选择锁房方式' }], onChange: changeHouseLockingType
          })(<Select placeholder="锁房方式" style={{ width: '300px' }}>
            <Option value="auto">自动锁房</Option>
            <Option value="manual">手动锁房</Option>
          </Select>)}
        </Form.Item>
        <Form.Item style={{ marginTop: '20px' }} label="认筹金额" help="最高50000元(需要微信商户号配置的行业为房地产行业：房地产开发，物业，房产中介。若微信商户号配置为其他行业则为3000元若不确定请联系平台相关运营人员。">
          {getFieldDecorator('raisePrice', {
            rules: [{ required: true, message: '请输入认筹金额' }],
          })(<InputNumber min={0.01} max={50000} step={0.01} placeholder="认筹缴费金额" style={{ width: '200px' }} />)}<span>元</span>
        </Form.Item>
        <Form.Item style={{ marginTop: '20px' }} label="认筹需预选" help="设置是否需要客户之前预选了房源才能认筹。">
          {getFieldDecorator('needPreselection', {
            initialValue: preSelectFlag === true ? 'true' : 'false',
            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', {
            initialValue: houseLockingType,
          })(
            <Checkbox.Group style={{ width: '100%' }}>
              <Checkbox value="onLine" disabled={houseLockingType == 'onLine' ? true : false}>线上缴费</Checkbox>
              <Checkbox value="offLine" disabled={houseLockingType == 'onLine' ? true : false}>
                线下缴费
                  </Checkbox>
            </Checkbox.Group>,
          )}
        </Form.Item>
        <Form.Item style={{ marginTop: '20px' }} label="线上缴费说明">
          {getFieldDecorator('payDescriptionOnline')(<TextArea placeholder="向客户说明线上缴费相关业务需求" style={{ height: '300px' }}></TextArea>)}
        </Form.Item>
        <Form.Item label="线下缴费说明">
          {getFieldDecorator('payDescriptionOffline')(<TextArea placeholder="填写线下缴费时间地点要求" style={{ height: '300px' }}></TextArea>)}
        </Form.Item>
        <Form.Item label="认筹单注意事项">
          {getFieldDecorator('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: '请输入选房协议' }],
          })(<Wangedit />)}
        </Form.Item>

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

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

const WrappedHeader = Form.create({ name: 'header' })(header);

export default WrappedHeader
