import React, { Component } from 'react';
import { connect } from 'dva';
import store from 'store';
import { withRouter } from 'dva/router';
import {
  Form,
  Input,
  Button,
  Icon,
  Modal,
  Alert,
  Card,
  List,
  Avatar,
  Select,
  message
} from 'antd';

import './less/depart.less';
// import * as ajax from "../../../services/api";
import {
  enterpriseInsComInsSaveBookScheme,
  enterpriseInsComInsGetBlbProList, //获取产品列表
  systemComVaseInfoGet //获取公司的省份信息
} from '../../../services/api';

// const { MenuItemGroup } = Menu;
const FormItem = Form.Item;
const { Option } = Select;
@connect(state => ({
  profile: state.profile,
  companyInfo: state.global.companyInfo
}))
@Form.create()
@withRouter

/**
 * 部门管理组件
 */
export default class GetPlanBook extends Component {
  constructor(props, context) {
    super(props, context);
    this.state = {
      insurancetipsvisible: this.props.insurancetipsvisible, //提示模板
      policyHolder: this.props.companyInfo.comName, //投保人
      regProvinceId: '', //企业所在省份
      regProvinceName: '', //所在省份对应的落地项目
      regProvinceAllName: '', //所在省份对应的落地项目(全称)
      contactper: '', //联系人
      contactPhone: '', //联系方式
      comPerNum: '', //企业人数
      guaranteeAmountLow: '', //保障金额下限
      insAmountUp: '', //保费上限
      accessbookvisible: false, //获取方案书
      disabled: true,
      productvisible: false, //选择产品
      productlistdata: [],
      isIns: this.props.isIns || ''
      // comName:"",//企业名称
    };
  }

  componentDidMount() {
    //450000-->广西壮族自治区,610000-->陕西省,640000-->宁夏回族自治区
    systemComVaseInfoGet({}).then(
      response => {
        const regProvince = response.data.regProvince;
        const regProvinceName =
          regProvince === 450000
            ? '广西'
            : regProvince === 610000
            ? '陕西省'
            : regProvince === 640000
            ? '宁夏'
            : regProvince === 110000
            ? '北京'
            : '';
        const regProvinceAllName =
          regProvince === 450000
            ? '广西壮族自治区'
            : regProvince === 610000
            ? '陕西省'
            : regProvince === 640000
            ? '宁夏回族自治区'
            : regProvince === 110000
            ? '北京市'
            : '';
        this.setState({
          regProvinceName,
          regProvinceId: regProvince,
          regProvinceAllName
        });
      },
      err => {
        console.log(err);
      }
    );
  }

  componentWillReceiveProps(nextprops) {
    if (
      nextprops.insurancetipsvisible &&
      nextprops.insurancetipsvisible !== this.state.insurancetipsvisible
    ) {
      this.setState({ insurancetipsvisible: nextprops.insurancetipsvisible });
    }
    if (
      nextprops.accessbookvisible &&
      nextprops.accessbookvisible !== this.state.accessbookvisible
    ) {
      this.setState({ accessbookvisible: nextprops.accessbookvisible });
    }

    if (nextprops.isIns !== this.state.isIns) {
      this.setState({ isIns: nextprops.isIns });
    }
  }

  handlenextpeopleOk = e => {
    //获取方案书表单提交
    e.preventDefault();
    this.props.form.validateFields((err, values) => {
      if (!err) {
        this.getProductList();
        const {
          contactper = '',
          contactPhone = '',
          comPerNum = '',
          guaranteeAmountLow = '',
          insAmountUp = '',
          proCode = ''
        } = values;
        const obj = {
          contactper,
          contactPhone,
          comPerNum,
          guaranteeAmountLow,
          insAmountUp,
          proCode
        };

        this.setState(obj);
        this.props.okorcancel('accessbookvisible', false);
        this.setState({
          accessbookvisible: false,
          productvisible: true
        });
      }
    });
  };

  // 选择产品
  chooseProductClick = (item, index) => {
    const productlistdata = [...this.state.productlistdata].map((val, key) => {
      if (key !== index) {
        val.isCheck = false;
      }
      if (key === index) {
        val.isCheck = true;
      }
      return val;
    });
    this.setState({ productlistdata });
  };

  handlereducepeopleCancel = () => {
    this.props.okorcancel('accessbookvisible', false);
    this.props.conGetPlanBook(false);
    this.setState({
      accessbookvisible: false,
      insurancetipsvisible: false
    });
  };

  handleproductxCancel = e => {
    this.props.okorcancel('productvisible', false);

    this.setState({
      productvisible: false
    });
  };
  handleproductCancel = () => {
    this.props.okorcancel('productvisible', false);

    this.setState({
      productvisible: false,
      accessbookvisible: true
    });
  };

  handlesurancetipxCancel = e => {
    this.props.okorcancel('insurancetipsvisible', false);

    this.setState({
      insurancetipsvisible: false
      // insurancetipvisible:true,
    });
  };

  handlesurancetipCancel = e => {
    this.props.okorcancel('insurancetipsvisible', false);

    this.setState({
      // insurancetipvisible: false,
      insurancetipsvisible: false
    });
    this.props.history.push(
      // 跳转到1-4-4
      '/enterprise/company'
    );
  };

  handlesuranceOk = e => {
    this.props.okorcancel('insurancetipsvisible', false);
    this.setState({
      insurancetipsvisible: false,
      accessbookvisible: true
    });
  };

  // 获取产品列表
  getProductList = () => {
    enterpriseInsComInsGetBlbProList({}).then(data => {
      const productlistdata = data.data.map(val => {
        return { ...val, ...{ isCheck: false } };
      });
      this.setState({ productlistdata });
      console.log('获取产品列表', data);
    });
  };

  handleproductOk = () => {
    const item = this.state.productlistdata.find(val => val.isCheck === true);
    if (!item) {
      message.error('请选择产品');
      return;
    }
    const {
      contactper,
      contactPhone,
      comPerNum,
      guaranteeAmountLow,
      insAmountUp
    } = this.state;

    enterpriseInsComInsSaveBookScheme({
      contactper,
      contactPhone,
      comPerNum,
      guaranteeAmountLow,
      insAmountUp,
      proCode: item.proCode,
      insBootName: `${item.nsBootName}方案书`
    }).then(
      res => {
        console.log('成功信息-方案书values', res);
        this.setState({ productvisible: false });
        this.props.history.replace('/insurancemanagement/insurancePlan');
      },
      err1 => {
        console.log('错误信息-err', err1);
      }
    );
  };

  // 温馨提示马上查看
  rightCheckClick = () => {
    this.props.history.push(`/insurancemanagement/enterpriseinsurance`);
  };

  render() {
    //获取方案书
    const { submitting } = this.props;
    const { getFieldDecorator } = this.props.form;
    const formItemLayout = {
      labelCol: {
        xs: { span: 7 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 15 },
        sm: { span: 15 },
        md: { span: 15 }
      }
    };
    const submitFormLayout = {
      wrapperCol: {
        xs: { span: 15, offset: 7 },
        sm: { span: 15, offset: 7 }
      }
    };
    const identification =
      this.state.regProvinceId === 610000
        ? '陕公治〔2017〕182 号'
        : this.state.regProvinceId === 450000
        ? '桂公网传〔2017〕110 号'
        : '';
    const reparations =
      this.state.regProvinceId === 450000
        ? '37'
        : this.state.regProvinceId === 610000
        ? '38'
        : this.state.regProvinceId === 640000
        ? '30'
        : this.state.regProvinceId === 110000
        ? '60'
        : '';
    return (
      <div className="getPlanBook">
        {/* 温馨提示 */}
        <Modal
          className="surancetip"
          title="温馨提示"
          visible={this.state.insurancetipsvisible}
          onOk={this.handlesuranceOk}
          onCancel={this.handlesurancetipxCancel}
          footer={false}
        >
          <div>
            {this.state.isIns === '0' && (
              <Alert
                message="很遗憾，贵公司未购买保险产品。请依照政策要求购买符合条件的保险产品。"
                type="warning"
                showIcon
              />
            )}
            {this.state.isIns === '1' && (
              <Alert
                message="很遗憾，贵司所投保人数不符合政策要求。请保证所有保安都已投保。"
                type="warning"
                showIcon
              />
            )}
            {this.state.isIns === '2' && (
              <Alert
                message="很遗憾，贵司所购买的保险保额不符合政策要求。请保证所有保安的总保障额度符合要求。"
                type="warning"
                showIcon
              />
            )}
            {this.state.isIns === '3' && (
              <Alert
                message="很遗憾，贵司所购买的保险保额和投保人数不符合政策要求。请依照政策要求购买。"
                type="warning"
                showIcon
              />
            )}
          </div>
          {this.state.isIns === '9' && (
            <p>
              恭喜贵司，已符合**地区保安从业单位应为保安员投保的相关政策要求，您还可继续投保为员工提高保障额度
            </p>
          )}
          {this.state.isIns !== '9' && this.state.regProvinceId !== 110000 && (
            <p>
              根据《关于启用{this.state.regProvinceId === 610000 ? '' : '新版'}
              {this.state.regProvinceName}
              {this.state.regProvinceId === 610000 ? '新版' : ''}
              保安服务监管信息系统有关工作的通知》{identification}
              及《保安服务管理条例》第四章第二十条规定，推进落实保安从业单位根据保安服务岗位的风险程度为保安员投保意外伤害保险，保险保障额度应当不低于
              {this.state.regProvinceAllName}人身损害赔偿标准（约{reparations}
              万），并通过本系统及时将投保情况实时向公安机关报备。
            </p>
          )}
          {this.state.isIns !== '9' && this.state.regProvinceId === 110000 && (
            <div>
              <p>
                《关于启用新版北京市保安服务监管信息系统有关工作的通知》明确规定：
              </p>
              <span>（1）根据《保安服务管理条例》第四章第二十条规定，推进落实保安从业单位根据保安服务岗位的风险程度为保安员投保意外伤害保险，按照系统要求填报录入投保信息（北京人身损害赔偿标准约为60万）。</span>
              <br/>
              <span>（2）未按照本通知规定给保安员投保意外伤害保险并通过新版系统将投保情况实时向公安机关报备，纳入企业等级评定考核。</span>
            </div>
          )}
          {/* {this.state.isIns === "9" && (
            <div className="intbtn">
              <Button key="back" onClick={this.handlesurancetipCancel}>
                已购买保险
              </Button>
              <Button key="submit" onClick={this.handlesuranceOk}>
                获取保险方案书
              </Button>
              <Button key="" type="primary" onClick={this.handleonline}>
                在线购买保险
              </Button>
            </div>
          )}
          {this.state.isIns === "1" && (
            <div className="intbtn">
              <Button key="submit" onClick={this.handlesuranceOk}>
                获取保险方案书
              </Button>
              <Button key="" type="primary" onClick={this.handleonline}>
                在线购买保险
              </Button>
            </div>
          )}
          {this.state.isIns === "2" && (
            <div className="intbtn">
              <Button key="submit" onClick={this.handlesuranceOk}>
                获取保险方案书
              </Button>
              <Button key="" type="primary" onClick={this.handleonline}>
                在线购买保险
              </Button>
            </div>
          )}
          {this.state.isIns === "3" && (
            <div className="intbtn">
              <Button key="submit" onClick={this.handlesuranceOk}>
                获取保险方案书
              </Button>
              <Button key="" type="primary" onClick={this.handleonline}>
                在线购买保险
              </Button>
            </div>
          )} */}
          {/* {this.state.isIns === "0" && ( */}
          <div className="intbtn">
            {/* <Button type="primary" key="back" onClick={this.rightCheckClick}>
                马上查看
              </Button> */}
            <Button
              type="primary"
              // key="submit"
              key="back"
              onClick={this.handlereducepeopleCancel}
            >
              我知道了
            </Button>
          </div>
          {/* )} */}
        </Modal>

        {/* 获取方案书 */}
        <Modal
          className="accessbook"
          title="获取方案书"
          visible={this.state.accessbookvisible}
          onOk={this.handlenextpeopleOk}
          onCancel={this.handlereducepeopleCancel}
          footer={null}
        >
          <div style={{ paddingBottom: 16 }}>
            <Form onSubmit={this.handleSubmit} style={{ marginTop: 24 }}>
              <FormItem {...formItemLayout} label="投保人">
                {getFieldDecorator('policyHolder', {
                  // {}
                  initialValue: this.state.policyHolder,
                  rules: [{ message: '请填写' }]
                })(<Input disabled={this.state.disabled} />)}
              </FormItem>
              <FormItem {...formItemLayout} label="联系人">
                {getFieldDecorator('contactper', {
                  initialValue: this.state.contactper,
                  rules: [{ required: true, message: '限制长度20位', max: 20 }]
                })(<Input placeholder="请填写" />)}
              </FormItem>
              <FormItem {...formItemLayout} label="联系方式">
                {getFieldDecorator('contactPhone', {
                  initialValue: this.state.contactPhone,
                  rules: [
                    { required: true, message: '请输入' },
                    { validator: this.checkPhone }
                  ]
                })(<Input placeholder="请填写" />)}
              </FormItem>
              <FormItem {...formItemLayout} label="企业人数">
                {getFieldDecorator('comPerNum', {
                  initialValue: this.state.comPerNum,
                  rules: [
                    { message: '限制长度7位数字', max: 7 },
                    { validator: this.checkpeoplenum }
                  ]
                })(<Input placeholder="请输入" />)}
              </FormItem>
              <FormItem {...formItemLayout} label="保障金额不低于">
                {getFieldDecorator('guaranteeAmountLow', {
                  initialValue: this.state.guaranteeAmountLow,
                  rules: [{ required: true, message: '请选择' }]
                })(
                  <Select placeholder="请选择">
                    <Option key="0" value="20">
                      20万
                    </Option>
                    <Option key="1" value="40">
                      40万
                    </Option>
                    <Option key="2" value="60">
                      60万
                    </Option>
                  </Select>
                )}
              </FormItem>
              <FormItem {...formItemLayout} label="保费不超过">
                {getFieldDecorator('insAmountUp', {
                  initialValue: this.state.insAmountUp,
                  rules: [{ required: true, message: '请选择' }]
                })(
                  <Select placeholder="请选择">
                    <Option key="0" value="600">
                      600元（不含600元）
                    </Option>
                    <Option key="1" value="400">
                      400元（不含400元）
                    </Option>
                    <Option key="2" value="200">
                      200元（不含200元）
                    </Option>
                  </Select>
                )}
              </FormItem>
              <FormItem {...submitFormLayout} style={{ marginBottom: 0 }}>
                <Button
                  loading={submitting}
                  onClick={this.handlereducepeopleCancel}
                >
                  晚点再看
                </Button>
                <Button
                  type="primary"
                  style={{ marginLeft: 8 }}
                  htmlType="submit"
                  onClick={this.handlenextpeopleOk}
                >
                  下一步
                </Button>
              </FormItem>
            </Form>
          </div>
        </Modal>
        {/* 选择产品 */}
        <Modal
          className="chooseproductlist"
          title="选择产品"
          visible={this.state.productvisible}
          onOk={this.handleproductOk}
          onCancel={this.handleproductxCancel}
          footer={[
            <Button key="back" onClick={this.handleproductCancel}>
              上一步
            </Button>,
            <Button key="submit" type="primary" onClick={this.handleproductOk}>
              保存
            </Button>
          ]}
        >
          <div className="chooseproduct">
            <Alert message="请选择您感兴趣的产品！" type="info" showIcon />
            <Card>
              <List
                itemLayout="horizontal"
                dataSource={this.state.productlistdata}
                renderItem={(item, index) => (
                  <List.Item
                    onClick={this.chooseProductClick.bind(this, item, index)}
                  >
                    <List.Item.Meta
                      avatar={<Avatar src={item.proImgPath} />}
                      title={<a>{item.insName}</a>}
                      description={
                        <div style={{ cursor: 'pointer' }}>
                          <div>{item.proIntro}</div>
                          <div className="premium">
                            保费：
                            <span className="guaranteebig">{item.insFee}</span>
                            <span
                              className="guaranteesm"
                              style={{ marginRight: 20 }}
                            >
                              元/人
                            </span>
                            保障金额：<span className="guaranteebig">60</span>
                            <span className="guaranteebigsm">万</span>
                            {item.isCheck && (
                              <Icon
                                type="check-circle-o"
                                className="productselect"
                              />
                            )}
                          </div>
                        </div>
                      }
                    />
                  </List.Item>
                )}
              />
            </Card>
          </div>
        </Modal>
      </div>
    );
  }
}
