import React,{Component} from 'react';
import {
    AutoComplete,
    Button,
    Cascader,
    DatePicker,
    Icon,
    Input,
    message,
    Modal,
    Select,
    Spin,
    Table,
    Tabs,
    Tag
} from "antd";
import { citySelect, provinceList } from '@/NewDicProvinceList';
import {getSocialAttribute, beforeUploadFile, getLevel, ShowModal} from "@/tools.js";
import moment from "moment";
import $ from "jquery/src/ajax";
import IntentionDetail from "../../NEW/intentionCustomer/intentionDetail/intentionDetail";

const {TabPane} = Tabs;
const { RangePicker } = DatePicker;

class CustomerFollow extends Component{
    constructor(props) {
        super(props);
        this.state={
            nameSearch: '',
            provinceSearch: '',
            addressSearch: '',
            level: '',
            releaseDate: [],
            selectedRowKeys: [],
            sortType: 0,

            provinces: [],
            dataSource: [],
            categoryArr: [],
            modalName: '',
            modalVisible: false,
            basicState: false,
            contactState: false,
            rowData: {},
            pagination: {
                defaultCurrent: 1,
                defaultPageSize: 10,
                showQuickJumper: true,
                pageSize: 10,
                onChange: function (page) {
                    this.loadData(page);
                }.bind(this),
                showTotal: function (total) {
                    return "共" + total + "条数据";
                },
            },
            columns: [
                {
                    title: "客户名称",
                    dataIndex: "name",
                    key: "name",
                },
                {
                    title: "地区",
                    dataIndex: "locationProvince",
                    key: "locationProvince",
                },
                {
                    title: "联系人",
                    dataIndex: "contacts",
                    key: "contacts",
                },
                {
                    title: "联系电话",
                    dataIndex: "contactMobile",
                    key: "contactMobile",
                },
                {
                    title: "社会性质",
                    dataIndex: "societyTag",
                    key: "societyTag",
                    render: (text) => {
                        return getSocialAttribute(text);
                    },
                },
                {
                    title: "客户初始时间",
                    dataIndex: "transferTime",
                    key: "transferTime",
                },
                {
                    title: "剩余私有天数",
                    dataIndex: "surplusFollowTime",
                    key: "surplusFollowTime",
                },
                {
                    title: "剩余签单天数",
                    dataIndex: "surplusSignTime",
                    key: "surplusSignTime",
                },
                {
                    title: "最新跟进时间",
                    dataIndex: "lastFollowTime",
                    key: "lastFollowTime",
                    //0无 1转换倒序 2转换正序
                    sorter: true,
                },
                {
                    title: "客户等级",
                    dataIndex: "level",
                    key: "level",
                    render: (text) => {
                        if(text === 0) {
                            return <Tag color="#87d068">一般客户</Tag>;
                        }else if(text === 1) {
                            return <Tag color="#D2691E">意向客户</Tag>;
                        }else if(text === 2) {
                            return <Tag color="#FF0000">重点客户</Tag>;
                        }else {
                            return "";
                        }
                    },
                },
                {
                    title: "跟进人",
                    dataIndex: "aName",
                    key: "aName",
                },
                {
                    title: "跟进操作",
                    dataIndex: "abc",
                    key: "abc",
                    render: (text, record, index) => {
                        return (
                            <div>
                                <Button
                                    onClick={(e) => {
                                        e.stopPropagation();
                                        this.setState({
                                            tabsKey:"4",
                                        },()=>{
                                            this.tableRowClick(record)
                                        })
                                    }}
                                    type="primary"
                                >
                                    {this.props.isEditGuidanceLv ? '指导' : '查看指导'}
                                </Button>
                            </div>
                        );
                    },
                },
            ],
            loading: false,
            ispage: 1,
            guidance: '',
            tabsKey:'',
        };
        this.callback = this.callback.bind(this);
        this.loadData = this.loadData.bind(this);
        this.reset = this.reset.bind(this);
        this.tableRowClick = this.tableRowClick.bind(this);
        this.closeDesc = this.closeDesc.bind(this);
        this.releaseGuidance = this.releaseGuidance.bind(this);
    }

    componentDidMount() {
        this.loadData();
        this.category();
        //城市
        let Province = [];
        provinceList.map(function (item) {
            let id = String(item.id);
            Province.push(
                <Select.Option value={id} key={item.name}>
                    {item.name}
                </Select.Option>
            );
        });
        this.setState({
            provinces: Province
        })
    }

    callback(){

    }

    loadData(pageNo) {
        this.setState({
            loading: true,
        });
        let api = '/api/admin/customer/listFollowManagement';
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + api,
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize,
                level: this.state.level ? this.state.level : undefined,
                name: this.state.nameSearch,
                province: !this.state.addressSearch.length
                    ? this.state.provinceSearch
                    : this.state.addressSearch[0],
                city: !this.state.addressSearch.length
                    ? ""
                    : this.state.addressSearch[1],
                startDate: this.state.releaseDate[0],
                endDate: this.state.releaseDate[1],
                sortType:this.state.sortType,
            },
            success: function (data) {
                let theArr = [];
                if (data.error.length !== 0) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    }
                } else {
                    for (let i = 0; i < data.data.list.length; i++) {
                        let thisdata = data.data.list[i];
                        let diqu =
                            (thisdata.province == null ? "" : thisdata.province) +
                            (thisdata.city == null ? "" : "-" + thisdata.city) +
                            (thisdata.area == null ? "" : "-" + thisdata.area);
                        thisdata.key = i;
                        thisdata.id = thisdata.uid;
                        thisdata.lastFollowTime = thisdata.lastFollowTime && thisdata.lastFollowTime.split(" ")[0];
                        thisdata.transferTime= thisdata.transferTime && thisdata.transferTime.split(" ")[0];
                        thisdata.surplusFollowTime= thisdata.surplusFollowTime && thisdata.surplusFollowTime.split(" ")[0];
                        thisdata.surplusSignTime= thisdata.surplusSignTime && thisdata.surplusSignTime.split(" ")[0];
                        thisdata.locationProvince= diqu;
                        theArr.push(thisdata);
                    }
                    this.state.pagination.current = data.data.pageNo;
                    this.state.pagination.total = data.data.totalCount;
                    if (data.data && data.data.list && !data.data.list.length) {
                        this.state.pagination.current = 0;
                        this.state.pagination.total = 0;
                    }
                    this.setState({
                        ispage: data.data.pageNo,
                        dataSource: theArr,
                        pagination: this.state.pagination,
                    });
                }
            }.bind(this),
        }).always(
            function () {
                this.setState({
                    loading: false,
                });
            }.bind(this)
        );
    };

    reset(){
        this.setState({
            nameSearch: '',
            provinceSearch: '',
            addressSearch: '',
            level: '',
            releaseDate: [],
            selectedRowKeys: [],
            sortType: 0,
        },()=>{
            this.loadData();
        });
    };

    //品类数据获取
    category() {
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/Varieties/getSuperList",
            data: {},
            success: function (data) {
                let thedata = data.data;
                let theArr = [];
                if (!thedata) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    }
                } else {
                    thedata.map(function (item, index) {
                        theArr.push({
                            value: item.id,
                            key: item.cname,
                        });
                    });
                }
                this.setState({
                    categoryArr: theArr,
                });
            }.bind(this),
        });
    }

    tableRowClick(record){      //key 控制弹窗初始显示第几级
        this.setState({
            selectedRowKeys: [],
            modalVisible: true,
            basicState: true,
            contactState: true,
            modalName: record.name,
            rowData: record,
        });
    };

    closeDesc(e, s) {
        this.setState({
            basicState: e,
            visitModul: e,
            modalVisible: e,
            showDesc: e,
            tabsKey: '',
        })
        if (s) {
            this.loadData(this.state.ispage);
        }
    }

    //发布指导意见
    releaseGuidance(){
        if(!this.state.guidance){
            message.info('指导意见不能为空')
            return;
        }
        this.setState({
            loading: true,
        });
        let _this = this;
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/customer/pushReleaseUser",
            data: {
                guidance: this.state.guidance,
            },
            success: function (data) {
                let thedata = data.data;
                if (!thedata) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    }
                }else {
                    message.success("发布成功");
                    _this.loadData(this.state.ispage);
                }

            }.bind(this),
        }).always(
            function () {
                this.setState({
                    loading: false,
                });
            }.bind(this)
        );
    }

    render() {
        return(
            <div className="user-content">
                <div className="content-title">
                    <span>指导意见</span>
                </div>
                <div className="user-search">
                    <Tabs
                        defaultActiveKey="1"
                        onChange={this.callback}
                        className="test"
                    >
                        <TabPane tab="搜索" key="1">
                            <Input
                                placeholder="客户名称"
                                value={this.state.nameSearch}
                                style={{ width: 150, marginRight: 10, marginLeft: 10 }}
                                onChange={(e) => {
                                    this.setState({ nameSearch: e.target.value });
                                }}
                            />
                            <Select
                                placeholder="省"
                                style={{ width: 80 }}
                                value={this.state.provinceSearch}
                                onChange={(e) => {
                                    this.setState({ provinceSearch: e });
                                }}
                            >
                                {this.state.provinces}
                            </Select>
                            <span style={{ marginRight: "10px" }}>
                              <Cascader
                                  options={citySelect()}
                                  value={this.state.addressSearch}
                                  placeholder="选择城市"
                                  onChange={(e, pre) => {
                                      this.setState({ addressSearch: e });
                                  }}
                              />
                            </span>
                            <Select
                                style={{ width: 120 }}
                                value={this.state.level}
                                onChange={(e) => {
                                    this.setState({ level: e });
                                }}
                                placeholder="请选择客户等级"
                            >
                                <Select.Option value="0">一般客户</Select.Option>
                                <Select.Option value="1">意向客户</Select.Option>
                                <Select.Option value="2">重点客户</Select.Option>
                            </Select>
                            <RangePicker
                                value={[
                                    this.state.releaseDate[0]
                                        ? moment(this.state.releaseDate[0])
                                        : null,
                                    this.state.releaseDate[1]
                                        ? moment(this.state.releaseDate[1])
                                        : null,
                                ]}
                                onChange={(data, dataString) => {
                                    this.setState({ releaseDate: dataString });
                                }}
                            />
                            <Button
                                type="primary"
                                style={{ marginLeft: "10px", marginRight: 10 }}
                                onClick={()=>{
                                    this.loadData();
                                }}
                            >
                                搜索
                            </Button>
                            <Button onClick={this.reset}>重置</Button>
                        </TabPane>
                    </Tabs>
                </div>
                <div className="patent-table">
                    <Spin spinning={this.state.loading}>
                        <Table
                            columns={this.state.columns}
                            dataSource={this.state.dataSource}
                            // rowSelection={rowSelection}
                            pagination={this.state.pagination}
                            onRowClick={this.tableRowClick}
                            onChange={(pagination, filters, sorter)=>{
                                //0 正序 1倒序
                                if(sorter.order === 'ascend'){              //倒序
                                    this.setState({
                                        sortType: 1
                                    },()=>{
                                        this.loadData(pagination.current)
                                    });
                                }else if (sorter.order === 'descend'){      //正序
                                    this.setState({
                                        sortType: 0
                                    },()=>{
                                        this.loadData(pagination.current)
                                    });
                                }else if (typeof sorter.order === 'undefined'){       //正常
                                    this.setState({
                                        sortType: 0
                                    },()=>{
                                        this.loadData(pagination.current)
                                    });
                                }

                            }
                            }
                        />
                    </Spin>
                </div>
                <IntentionDetail
                    isGuidanceLv={this.props.isGuidanceLv}
                    isEditGuidanceLv={this.props.isEditGuidanceLv}
                    categoryArr={this.state.categoryArr}
                    detailApi={this.props.detailApi}
                    IntentionData={this.state.rowData}
                    modalVisible={this.state.modalVisible}
                    tabsKey={this.state.tabsKey}
                    name={this.state.modalName}
                    closeDesc={this.closeDesc}
                    basicState={this.state.basicState}
                    contactState={this.state.contactState}
                />
                <Modal
                    className="customeDetails"
                    title="指导意见"
                    width='500px'
                    visible={this.state.guidanceVisible}
                    onOk={()=>{
                        this.setState({
                            guidanceVisible: false,
                            guidance: '',
                        },()=>{
                            this.loadData(this.state.ispage);
                        })
                    }}
                    onCancel={()=>{
                        this.setState({
                            guidanceVisible: false,
                            guidance: '',
                        },()=>{
                            this.loadData(this.state.ispage);
                        })
                    }}
                    footer=''
                >
                    <Spin spinning={this.state.loading}>
                        <div style={{
                            display:'flex',
                            flexFlow:'column',
                        }}>
                            <Input
                                style={{ width: '400px',height:'50px' }}
                                placeholder="请输入指导意见"
                                type={'textarea'}
                                onChange={(e)=>{
                                    this.setState({
                                        guidance: e.target.value,
                                    })
                                }}
                            />
                            <Button
                                type="primary"
                                style={{ marginTop: "10px", marginBottom: '10px' }}
                                onClick={()=>{
                                    this.releaseGuidance();
                                }}
                            >
                                确定
                            </Button>
                        </div>
                    </Spin>
                </Modal>
            </div>
        )
    }
}

export default CustomerFollow;