import React, { Component } from 'react';
import st from 'styled-components';
import { connect } from 'dva';
import {
    Button,
    Alert,
    Popover,
    Input,
    Select,
    Modal,
    notification,
    Upload,
    Icon,
    message
} from 'antd';
import { withRouter } from 'dva/router';
import DepartSelect from '../../../../../components/user/DepartSelect';
import {
    findYIncumbencyPerCount,
    findOfflineOrOnlinePolicy,
    saveInsBlbMinusPreservationService,
    minusBatchRelevancePer,
    enterpriseInsComInsMinusBatchUploadInsPer,
    enterpriseInsComInsExportErrInsPer
} from '../../../../../services/api';

import columnFun from './columns';
import DelModal from './DelModal';
import tablePage from '../../../../../utils/hoc/tablePage';
import 
    // ExcelButtonOline,
    {excelButtonHOC}
 from '../../../../../components/ExcelButtonOline';
import $loading from '../../../../../utils/loading';

const { Option } = Select;
@connect(state => ({
    global: state.global
}))
@tablePage()
@withRouter
export default class Insured extends Component {
    constructor(props, context) {
        super(props, context);
        this.state = {
            policeys: [{
                value: '', comInsId: "", label: "全部", orderId: "",
                buyMode: 0   // 不区分线上线下
            }], //保险列表
            quitCount: 0, //离职在保数量
            selectedRows: [], //表格中选中的数组
            selectedRowKeys: [],
            importModal: false,  // 第一个导入模态框的显示
            delModal: false, // 下一个导入模态框
            importInfo: {}, //导入后接口返回的数据
        };
    }


    componentWillMount() {
        this.__getQuitCount();
        this.__getPolicey();
    }
    // 获取离职在保人数
    __getQuitCount() {
        findYIncumbencyPerCount().then(res => {
            this.setState({
                quitCount: res.data
            });
        })
    }
    // 获取保单列表下拉菜单
    __getPolicey = (cb) => {
        // 线上保单
        findOfflineOrOnlinePolicy({ buyMode: 1 }).then(res => {
            const onlineList = res.data.map(item => {
                item.value = item.comInsId + '-' + item.orderId + '-' + item.buyMode;  //线上
                return item;
            });
            //线下保单
            findOfflineOrOnlinePolicy({ buyMode: 2 }).then(result => {
                const outlineList = result.data.map(item => {
                    item.value = item.comInsId + '-' + item.orderId + '-' + item.buyMode; //线下
                    return item;
                });
                this.setState({
                    policeys: [...this.state.policeys, ...onlineList, ...outlineList]
                }, () => {
                    console.log(this.state.policeys, 'policeys')
                });
            });
        });
    }
    // 表格渲染
    __renderTable = () => {
        const columns = columnFun.call(this);
        const { PageTable, isInit } = this.props;
        if (!isInit) return;
        return (
            <PageTable
                columns={columns}
                url="findUnderWarrantyPerList"
                rowSelection={{
                    onChange: (selectedRowKeys, selectedRows) => {
                        this.setState({
                            selectedRows,
                            selectedRowKeys
                        });
                    },
                    selectedRowKeys: this.state.selectedRowKeys
                }}
                dateChange={data => {
                    this.props.getTotal(data.other);
                }}
                pagination={{
                    onChange: (page, pageSize) => {
                        this.setState({
                            selectedRows: [], //表格中选中的数组
                            selectedRowKeys: [],
                        });
                    }
                }}
            // scroll={{ x: '1600px' }}
            />
        );
    };

    render() {
        const { SearchForm, Form } = this.props;
        const { getFieldDecorator, setFieldsValue, getFieldValue } = this.props.form;
        const { importInfo, delModal, importModal } = this.state;
        return (
            <Container>
                {
                    this.state.quitCount > 0 ? <Alert
                        message={<div>当前有{this.state.quitCount}个已离职人员未退保，请逐单处理，若对应的保单过期了，则会自动将已投保人员变更为未投保状态；
                    <br />
                    减员：可将已投保人员移出投保单（退保），请先筛选保单，再选择需要减员的人员，点击 <span style={{ color: '#f5222d' }}>减员</span> 按钮，进行操作。</div>}
                        type="warning"
                        showIcon
                        style={{ marginBottom: '15px' }}
                    /> : ''
                }
                <SearchForm
                    arrange={values => {
                        values.departId = values.departId.split('-')[0];
                        const comInsIdvalue = values.comInsId;
                        values.comInsId = comInsIdvalue.split('-')[0];
                        const orderId = comInsIdvalue.split('-')[1];
                        const buyMode = comInsIdvalue.split('-')[2];
                        console.log(values.comInsId,orderId, buyMode), 'values';
                        this.setState({
                            comInsId: values.comInsId,
                            orderId,
                            buyMode
                        });
                        // 重置选中项
                        this.setState({
                            selectedRows: [], //表格中选中的数组
                            selectedRowKeys: [],
                        });
                        // this.setState({
                        //     params: values //储存参数，供导出使用
                        // });
                        return values;
                    }}
                >
                    <Form.Item label="选择保单">
                        {getFieldDecorator('comInsId', {
                            initialValue: ''
                        })(
                            <Select style={{ minWidth: 600 }}>
                                {this.state.policeys.map((item, index) => {
                                    return (
                                        <Option key={index} value={item.value}>{item.label}</Option>
                                    );
                                })}
                            </Select>
                        )}
                    </Form.Item>
                    <br />
                    <Form.Item label="关键词">
                        {getFieldDecorator('keyword', {
                            initialValue: ''
                        })(
                            <Input style={{ width: 240 }} placeholder="请输入姓名/手机号码/身份证" />
                        )}
                    </Form.Item>
                    <Form.Item label="部门">
                        {getFieldDecorator('departId', {
                            initialValue: ''
                        })(
                            <DepartSelect
                                showAll={true}
                                style={{ width: 240 }}
                                className="w-400 ipt-h"
                                dropdownStyle={{ maxHeight: 250, overflow: 'auto' }}
                                placeholder="请选择部门(默认为全部)"
                                treeDefaultExpandAll
                                allowClear
                                // showSearch={true}
                                // multiple
                                showCheckedStrategy={'SHOW_ALL'}
                            />
                        )}
                    </Form.Item>
                    <Form.Item label="就职状态">
                        {getFieldDecorator('isIncumbency', {
                            initialValue: ''
                        })(
                            <Select style={{ width: 240 }}>
                                <Option key="" value="">全部</Option>
                                <Option key="0" value="0">离职</Option>
                                <Option key="1" value="1">在职</Option>
                            </Select>
                        )}
                    </Form.Item>
                </SearchForm>
                <Btns>
                    <Popover content={
                        <div style={{ padding: '5px 10px' }}>
                            <p style={{ margin: 0 }}>请选择保单</p>
                        </div>
                    }>
                        <Button
                            type="primary"
                            // disabled={this.props.searchData.comInsId == ''}
                            disabled={!this.state.comInsId}
                            onClick={() => {
                                // const comInsId = getFieldValue('comInsId').split('-')[0];
                                // const orderId = getFieldValue('comInsId').split('-')[1];
                                // const buyMode = getFieldValue('comInsId').split('-')[2];
                                // log(comInsId, 'comInsId');
                                // log(orderId, 'orderId');
                                // log(buyMode, 'buyMode');
                                const { comInsId, orderId, buyMode } = this.state;
                                // console.log(comInsId, orderId, buyMode , 'comInsId, orderId, buyMode ')
                                if (this.state.selectedRows.length == 0) {
                                    notification.error({
                                        message: '请选择人员'
                                    });
                                } else {
                                    Modal.confirm({
                                        title: '是否为选中的人员进行减员操作？',
                                        okText: '确定',
                                        content: (<div>
                                            <p>关联线下保单，则直接移除关联；</p>
                                            <p>关联线上保单，则提交减员申请。（一次最多减员100人）</p>
                                        </div>),
                                        okText: '确认',
                                        onOk: () => {
                                            //   const { orderId, comInsId } = this.state;  
                                            // 线上保单
                                            if (buyMode == 1) {
                                                if (this.state.selectedRows.length > 100) {
                                                    return notification.error({
                                                        message: '一次关联人数不超过100个'
                                                    });
                                                }
                                                const perIds = this.state.selectedRows.reduce((a, b) => {
                                                    return a + ',' + b.perId;
                                                }, '').slice(1);
                                                saveInsBlbMinusPreservationService({ orderId, perIds }).then(res => {
                                                    Modal.success({
                                                        title: '提交减员申请成功！',
                                                        content: <p className="modal_tip left0">注：关联线上保单时，需要等待保险公司审核，请在<a>批单申请记录中</a>查看进度。</p>
                                                    });
                                                    this.props.updateTable();
                                                    // 重置选中项
                                                    this.setState({
                                                        selectedRows: [], //表格中选中的数组
                                                        selectedRowKeys: [],
                                                    });
                                                });
                                            } else {  //线下
                                                const idCards = this.state.selectedRows.reduce((a, b) => {
                                                    return a + ',' + b.idCardNo;
                                                }, '').slice(1);
                                                minusBatchRelevancePer({ idCards, comInsId }).then(res => {
                                                    // Modal.success({
                                                    //   title: '移除成功！',
                                                    //   content: <p className="modal_tip left0">已将所选选择人员移除保障状态！</p>
                                                    // });
                                                    Modal.confirm({
                                                        title: '上传批单提示',
                                                        okText: '确定',
                                                        content: (<div>
                                                            <p style={{ color: 'red' }}>*企业若发生人员变动，可通过【保险保单管理】-【修改】上传批单，后台将进行人工校验，请务必上传真实有效数据！</p>
                                                            <p>本次共移除<span style={{ color: 'red' }}>{this.state.selectedRows.length}</span>位，请及时上传相应批单！</p>
                                                        </div>),
                                                        okText: '马上办理',
                                                        cancelText: '取消',
                                                        onOk: () => {
                                                            this.props.history.push(`/insurancemanagement/enterpriseinsurance/insurancedetails?comInsId=${comInsId}&edit=00`);
                                                        }
                                                    });
                                                    // 重置选中项
                                                    this.setState({
                                                        selectedRows: [], //表格中选中的数组
                                                        selectedRowKeys: [],
                                                    });
                                                    this.props.updateTable();
                                                });
                                            }
                                        },
                                        cancelText: '取消'
                                    });
                                }
                            }}
                        >
                            批量减员
                        </Button>
                    </Popover>
                    <Popover
                        content={
                            <div style={{ padding: 10 }}>搜索后可导出</div>
                        }
                    >
                        {/* <ExcelButtonOline
                            disabled={!this.state.clicked}
                            method="POST"
                            params={this.state.searchData}
                            apiurl={"/enterprise/ins/com-ins/export-under-warranty-per-list"}
                            downloadname={this.props.global.companyInfo.comName + "_已投保人员"}
                        >
                            导出筛选结果为excel
                        </ExcelButtonOline> */}
                        {
                            excelButtonHOC({
                                disabled: !this.props.clicked,
                                method: 'POST',
                                params: this.props.searchData,
                                apiurl: "/enterprise/ins/com-ins/export-under-warranty-per-list",
                                downloadname: this.props.global.companyInfo.comName + "_已投保人员",
                                children: '导出筛选结果为excel'
                            }, Button)
                        }
                    </Popover>
                    <Button
                        type="primary"
                        onClick={() => {
                            this.setState({
                                importInfo: {},  //清空原来数据
                                importModal: true
                            });
                        }}
                    >
                        导入减员
                    </Button>
                </Btns>
                {/* 表格 */}
                {this.__renderTable()}


                <Modal
                    title="导入减员"
                    okText="下一步"
                    cancelText="取消"
                    visible={importModal}
                    okButtonProps={{ disabled: importInfo.successCount && importInfo.successCount > 0 ? false : true }}
                    onOk={() => {
                        this.setState({
                            importModal: false,
                            delModal: true
                        });
                    }}
                    onCancel={() => {
                        this.setState({
                            importModal: false
                        });
                    }}
                >
                    <a href="/files/雇主人员范本.xls" target="_blank">点击下载导入减员模板</a>
                    <div style={{ marginTop: 15 }}>
                        减员人员数据：
                        <Upload
                            showUploadList={false}
                            style={{ display: 'inline-block' }}
                            beforeUpload={(file) => {
                                let canUpload = true;
                                if (!(file.name + '').toLocaleLowerCase().match(/(\.xls)|(\.xlsx)/)) {
                                    message.error(`请上传拓展名为.xls或.xlsx的文件!`);
                                    canUpload = false;
                                }
                                return canUpload;
                            }}
                            customRequest={({ file }) => {
                                const formData = new FormData();
                                formData.append('xfile', file);
                                $loading.open('文件导入中,请稍后。。。');
                                enterpriseInsComInsMinusBatchUploadInsPer(formData, false).then(res => {
                                    $loading.close();
                                    // message.success('上传成功');
                                    this.setState({
                                        importInfo: res.data
                                    });
                                    this.props.updateTable();
                                }).catch(ex => {
                                    $loading.close();
                                    console.log(ex);
                                });
                            }}
                        >
                            <Button
                                style={{ marginLeft: 10 }}
                            >
                                <Icon type="upload" />上传文件
                            </Button>
                        </Upload>
                    </div>
                    <p>
                        支持扩展名：.xls 请下载模板并在模板中完善信息后导入，减员人员需为系统已导入人员。
                    </p>

                    {
                        importInfo.errCount && importInfo.errCount > 0 &&
                        <p style={{ color: '#D9001B', marginTop: 15 }}>
                            有人员数据无法识别，请下载失败文件查看，调整人员后重新导入
                            <br />
                            <a onClick={() => {
                                const { importBatchId } = this.state.importInfo;
                                enterpriseInsComInsExportErrInsPer({ importBatchId }).then(res => {
                                    if (!res) {
                                        return;
                                    }
                                    let url = window.URL.createObjectURL(res.data);
                                    let link = document.createElement('a');
                                    link.style.display = 'none';
                                    link.href = url;
                                    link.setAttribute(
                                        'download',
                                        `导入减员失败文件.xls`
                                    );
                                    document.body.appendChild(link);
                                    link.click();
                                });
                            }}>下载失败文件</a>
                        </p>
                    }
                </Modal>

                <DelModal
                    visible={delModal}
                    importInfo={importInfo}
                    setState={this.setState.bind(this)}
                    updateTable={this.props.updateTable}
                />
            </Container>
        );
    }
}


const Btns = st.div`
  margin-top: 15px;
  button {
    margin-right: 15px;
  }
`;
const Container = st.div`
  padding: 24px;
  padding-top: 0;
`;
