import React,{Component} from "react";
import {
    AutoComplete,
    Button,
    Cascader,
    DatePicker,
    Input,
    message,
    Select,
    Spin,
    Table,
    Tabs,
    Tooltip,
    Upload,
    Modal, Tag
} from "antd";
import {ChooseList} from "../../../order/orderNew/chooseList";
import $ from "jquery/src/ajax";
import {
    getSocialAttribute,
    ShowModal,
    getChannelAllocationStatus
} from "@/tools.js";
import {
    channelAllocationStatus
} from "@/dataDic.js";
import { citySelect, provinceList } from '@/NewDicProvinceList';
import moment from "moment";
import FollowDetail from "./followDetail";
import IntentionDetail from "./intentionDetail/intentionDetail";
import TransferRecords from './transferRecords';
import DuplicateData from './duplicateData';
import OperationTips from './operationTips';
import ShowModalDiv from "@/showModal.jsx";
import './channel.less';
import EnterpriseNameChange from "../../../../common/enterpriseNameChange";
const {TabPane} = Tabs;
const { RangePicker } = DatePicker;
const Option = Select.Option;
class Channel extends Component{
    constructor(props) {
        super(props);
        this.state={
            isGuidance:false,
            isEditGuidance: true,
            upLoadFileLoading:false,
            channelAllocationStatusList : channelAllocationStatus.slice(0,channelAllocationStatus.length-2),
            columns: [
                {
                    title: "客户名称",
                    dataIndex: "userName",
                    key: "userName",
                    render: (text,record) => {
                        return (
                            
                                {record.recovery === 1 ? 
                                    回收
                                
 : null}
                                
                                    {text}
                                 
				            
                        )
                    },
                },
                {
                    title: "地区",
                    dataIndex: "locationProvince",
                    key: "locationProvince",
                },
                {
                    title: "社会性质",
                    dataIndex: "societyTag",
                    key: "societyTag",
                    render: (text) => {
                        return getSocialAttribute(text);
                    },
                },
                {
                    title: "外联专员",
                    dataIndex: "channelName",
                    key: "channelName",
                },
                {
                    title: "客户联系人",
                    dataIndex: "contacts",
                    key: "contacts",
                },
                {
                    title: "联系电话",
                    dataIndex: "contactMobile",
                    key: "contactMobile",
                },
                {
                    title: "外联初始时间",
                    dataIndex: "createTimes",
                    key: "createTimes",
                },
                {
                    title: "分配状态",
                    dataIndex: "status",
                    key: "status",
                    render: (text) => (
                        getChannelAllocationStatus(text,true)
                    )
                },
            ],
            changeList:[],
            dataSource:[],
            pagination: {
                defaultCurrent: 1,
                defaultPageSize: 10,
                showQuickJumper: true,
                pageSize: 10,
                onChange: function (page) {
                    this.loadData(page);
                }.bind(this),
                showTotal: function (total) {
                    return "共" + total + "条数据";
                },
            },
            pageNo:1,
            listLoading:false,
            selectedRowKeys:[],
            selectedRows:[],
            modalVisible:false,
            nameSearch:'',
            statusSearch:undefined,
            provinceSearch:undefined,
            addressSearch:[],
            releaseDate:[],
            upLoad: {
                customRequest: (options) => {
                    this.setState({
                        upLoadFileLoading: true,
                    })
                    let params = new FormData();
                    params.append("file", options.file);
                    $.ajax({
                        method: "post",
                        url: globalConfig.context + "/api/user/channel/import",
                        async: true,
                        cache: false,
                        contentType: false,
                        processData: false,
                        data:params
                    }).done(
                        function (data) {
                            this.setState({
                                upLoadFileLoading: false,
                            })
                            if (data.error.length === 0) {
                                if(data.data === 1){
                                    message.success("导入成功!");
                                }else if(data.data.list.length > 0){
                                    message.warning('已成功导入!错误/重复客户无法导入,请查看错误外联数据!');
                                    this.setState({
                                        duplicateData: [],
                                        duplicateDataVisible: true
                                    })
                                }
                                this.loadData();
                            } else {
                                message.warning(data.error[0].message);
                                this.loadData();
                            }
                        }.bind(this)
                    ).always(
                        function () {
                            this.loadData();
                            this.setState({
                                upLoadFileLoading: false,
                            });
                        }.bind(this)
                    );
                },
                name: "file",
                action: globalConfig.context + "/api/user/channel/import",
            },
            followData: '',
            visitModul: false,
            categoryArr:[],
            tabsKey:'',
            adminList:[],
        }
        this.loadData = this.loadData.bind(this);
        this.search = this.search.bind(this);
        this.reset = this.reset.bind(this);
        this.changeList = this.changeList.bind(this);
        this.download = this.download.bind(this);
        this.category = this.category.bind(this);
        this.closeDesc = this.closeDesc.bind(this);
        this.guidanceRead = this.guidanceRead.bind(this);
        this.tableRowClick = this.tableRowClick.bind(this);
        this.detailCloseDesc = this.detailCloseDesc.bind(this);
        this.supervisor = this.supervisor.bind(this);
        this.httpChange = this.httpChange.bind(this);
        this.blurChange = this.blurChange.bind(this);
        this.selectAuto = this.selectAuto.bind(this);
        this.changeAssigner = this.changeAssigner.bind(this);
        this.getAdminList = this.getAdminList.bind(this);
    }
    componentWillReceiveProps (nextProps) {
        let next = JSON.stringify(nextProps);
        let props = JSON.stringify(this.props);
        if(next !== props){
            location.reload();
        }
    }
    componentDidMount() {
        this.initialization();
    }
    //获取外联专员列表
    getAdminList(value = '') {
        this.setState({
            adminListLoading:true
        })
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/superviser/adminList",
            data: {
                pageNo: 1,
                pageSize: 99,
                name: value,
                roleName: '外联专员',
            },
            success: function (data) {
                let thedata = data.data.list;
                let theArr = [];
                if (data.error && data.error.length) {
                    message.warning(data.error[0].message);
                }else{
                    thedata.map(function (item, _) {
                        theArr.push({
                            value: item.id,
                            label: item.name,
                        });
                    });
                }
                this.setState({
                    adminList: theArr,
                });
            }.bind(this),
        }).always(
            function () {
                this.setState({
                    adminListLoading:false
                })
            }.bind(this)
        );
    }
    initialization(){
        //城市
        let provinces = [];
        provinceList.map(function (item) {
            var id = String(item.id);
            provinces.push(
                
                    {item.name}
                
            );
        });
        this.setState({
            provinces
        })
        this.loadData();
        this.category();
        if(this.props.type === 0 || this.props.type === 3){
            this.state.columns.push({
                title: "分配时间",
                dataIndex: "distributionTimes",
                key: "distributionTimes",
            });
            this.state.columns.push({
                title: "剩余签单(天)",
                dataIndex: "days",
                key: "days",
                render: (text,record) => (
                    record.status !== 7 ? {text}天 : ''
                )
            });
        }
        if(this.props.followUp){
            this.state.columns.push({
                title: "当前跟进人",
                dataIndex: "adminName",
                key: "adminName",
                render: (text, record) => {
                    return (
                        record.status !== 0 ? text : ''
                    )
                }
            });
            this.state.columns.push({
                title: "跟进操作",
                dataIndex: "abc",
                key: "abc",
                render: (text, record, index) => {
                    return (
                        
                            
                        
                    );
                },
            });
            if(this.props.isEditGuidanceLv){
                this.state.columns.push({
                    title: "指导意见",
                    dataIndex: "guidance",
                    key: "guidance",
                    render: (text, record, index) => {
                        return (
                            
                                {/*指导 0无 1未读 2已读*/}
                                {text === 1 || text === 2 ? 
 : 
暂无指导
}
                            
{text}
                    
                )
            }
        });
        this.setState({
            columns:this.state.columns
        })
    }
    visit(e) {
        this.setState({
            followData: e,
            visitModul: true,
        });
    }
    loadData(pageNo = 1) {
        this.setState({
            listLoading: true,
            selectedRows: [],
            selectedRowKeys: [],
        });
        $.ajax({
            method: "post",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + '/api/admin/customer/listChannelCustomer',
            data: {
                type:this.props.type,
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize,
                name: this.state.nameSearch,
                status:this.state.statusSearch,
                province: !this.state.addressSearch.length
                    ? this.state.provinceSearch
                    : this.state.addressSearch[0],
                city: !this.state.addressSearch.length
                    ? ""
                    : this.state.addressSearch[1],
                startTime: this.state.releaseDate[0],
                endTime: this.state.releaseDate[1],
                aid:this.state.adminValue,
            },
            success: function (data) {
                ShowModal(this);
                let theArr = [];
                if (data.error.length > 0) {
                    message.warning(data.error[0].message);
                } else {
                    if(data.data.list.length === 0 && pageNo !== 1){
                        this.loadData(pageNo - 1)
                    }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;
                        this.setState({
                            pageNo: data.data.pageNo,
                            dataSource: theArr,
                            pagination: this.state.pagination,
                        })
                    }
                }
            }.bind(this),
        }).always(
            function () {
                this.setState({
                    listLoading: false,
                });
            }.bind(this)
        );
    }
    search(){
        this.loadData();
    }
    reset(){
        this.setState({
            nameSearch:'',
            provinceSearch:undefined,
            addressSearch:[],
            releaseDate:[],
            statusSearch:undefined,
            adminValue:undefined,
        },()=>{
            this.loadData();
        })
    }
    download() {
        window.location.href =
            globalConfig.context +
            "/api/user/channel/downloadTemplate?" +
            "sign=user_channel";
    }
    changeList(arr) {
        const newArr = [];
        this.state.columns.forEach(item => {
            arr.forEach(val => {
                if (val === item.title) {
                    newArr.push(item);
                }
            });
        });
        this.setState({
            changeList: newArr
        });
    }
    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);
                    }
                    thedata = {};
                } else {
                    thedata.map(function (item, index) {
                        theArr.push({
                            value: item.id,
                            key: item.cname,
                        });
                    });
                }
                this.setState({
                    categoryArr: theArr,
                });
            }.bind(this),
        });
    }
    closeDesc(){
        this.setState({
            followData:'',
            visitModul:false
        })
    }
    //已读指导记录
    guidanceRead(id) {
        return new Promise((resolve,reject)=>{
            $.ajax({
                method: "post",
                dataType: "json",
                crossDomain: false,
                url: globalConfig.context + "/api/admin/customer/pushGuidance",
                data: {
                    uid: id,
                }
            }).done(function(data) {
                if(!data.error.length) {
                    resolve();
                } else {
                    message.warning(data.error[0].message);
                    reject();
                };
            }.bind(this));
        })
    }
    tableRowClick(record) {
        if(this.props.deliver === 2 && record.status === 2 && this.props.isEditGuidanceLv){
            this.setState({
                isGuidance: true,
                tabsKey:"4",
            })
        }
        //营销经理人员 取消指导自己的操作
        if(this.props.deliver === 2 && record.status === 1 && this.props.isEditGuidanceLv){
            this.setState({
                isEditGuidance: false,
            })
        }
        //营销人员 取消指导的操作
        if(this.props.deliver === 0 && record.status === 2 && this.props.isEditGuidanceLv){
            this.setState({
                isEditGuidance: false,
            })
        }
        this.setState({
            rowData:record,
            modalVisible: true,
            basicState: true,
            contactState: true,
            modalName: record.userName
        })
    }
    detailCloseDesc(){
        this.setState({
            rowData:'',
            modalVisible: false,
            basicState: false,
            contactState: false,
            modalName: '',
            isGuidance: false,
            isEditGuidance: true,
            tabsKey: '',
        },()=>{
            this.loadData(this.state.pageNo);
        })
    }
    supervisor(e) {
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/customer/listAdminByName",
            data: {
                adminName: e,
            },
            success: function (data) {
                let thedata = data.data;
                if (!thedata) {
                    if (data.error && data.error.length) {
                        message.warning(data.error[0].message);
                    }
                    thedata = {};
                }
                this.setState({
                    customerArr: thedata,
                });
            }.bind(this),
        }).always(
            function () {
            }.bind(this)
        );
    }
    httpChange(e) {
        if (e.length >= 1) {
            this.supervisor(e);
        }
        this.setState({
            auto: e,
        });
    }
    blurChange(e) {
        let theType = "";
        let contactLists = this.state.customerArr || [];
        if (e) {
            contactLists.map(function (item) {
                if (item.name == e.toString()) {
                    theType = item.id;
                }
            });
        }
        this.setState({
            theTypes: theType,
        });
    }
    selectAuto(value, options) {
        this.setState({
            auto: value,
        });
    }
    changeAssigner(remarks,type,lv) {
        //type   0 总监分配 1经理分配 2回收
        let arr = this.state.selectedRows.filter(v=>v.status === 1);
        let arr1 = this.state.selectedRows.filter(v=>v.status === 2);
        let arr2 = this.state.selectedRows.filter(v=>v.status === 7);
        let arr3 = this.state.selectedRows.filter(v=>v.status === 6);
        if(type === 0 && (arr.length>0 || arr1.length>0)){
            message.warning('选中的信息中存在“已分配”数据,请取消这些选项后重新提交')
            return;
        }
        if(type === 1 && arr1.length>0){
            message.warning('选中的信息中存在“经理已分配”数据,请取消这些选项后重新提交')
            return;
        }
        //处于回收状态的客户经理和营销员不能点击回收
        if(this.props.deliver !== 1 && arr3.length>0){
            message.warning('外联客户已回收!待营销总监,重新分配')
            return;
        }
        //this.props.deliver && this.props.recovery   用于判断是否为经理
        if(this.props.deliver === 2 && this.props.recovery && type === 2 && arr1.length>0){
            message.warning('操作失败,存在客户已被分配营销员')
            return;
        }
        if(arr2.length>0){
            message.warning('不能操作已签单客户')
            return;
        }
        if(!remarks){
            message.warning(type === 1 ? "请输入分配原因" : type === 2 ? "请输入回收原因" : type === 0 ? "请输入分配原因" : "");
            return;
        }
        if (this.state.theTypes || lv) {
            this.setState({
                listLoading: true,
            })
            let changeIds  = '';
            let oldAid = '';
            for (let idx = 0; idx < this.state.selectedRows.length; idx++) {
                let rowItem = this.state.selectedRows[idx];
                if(rowItem.recovery === 1 && type === 2){
                    let arr = this.state.selectedRows.filter(v => v.recovery === 1)
                    Modal.info({
                        title: '以下数据属于回收再分配资源,无法再次回收',
                        content: (
                            
                                {
                                    arr.map(i=>(
                                        
{i.userName}
                                    ))
                                }
                            
                
                
                    外联客户
                
                
                    
                        
                             {
                                    this.setState({ nameSearch: e.target.value });
                                }}
                            />
                            
                            
                            
                               {
                                      this.setState({ addressSearch: e });
                                  }}
                              />
                            
                             {
                                    this.setState({ releaseDate: dataString });
                                }}
                            />
                            {this.props.type !== 1 ?  : null}
                            
                            
                        
                        
                            
                                {this.props.deliver ? 
                                    
                                 : ''}
                                {this.props.deliver ? 
 : ''}
                                {this.props.recovery ? 
 : ''}
                                {this.props.deliver || this.props.recovery ? 
 : ''}
                                {this.props.channel ? 
                                    
                                 : null}
                                {this.props.channel ? 
 : ''}
                                {this.props.channel ? 
 : ''}
                                
                            
                                
                            
                        
                    
                 
                
                
                
                {this.state.duplicateDataVisible ? 
{
                        this.setState({
                            duplicateData:[],
                            duplicateDataVisible: false
                        },()=>{
                            this.loadData(this.state.pageNo);
                        })
                    }}
                /> : null}
                {this.state.transferVisible || this.state.returnVisible ? {
                        this.setState({
                            transferVisible:false,
                            returnVisible: false,
                            transferId:''
                        })
                    }}
                /> : '' }
                {/*外联客户分配*/}
                {this.state.visible ? {
                        // 0 总监分配 1经理分配 2回收
                        this.changeAssigner(value,this.props.deliver === 1 ? 0 : this.props.deliver === 2 ? 1 : '')
                    }}
                    onCancel={()=>{
                        this.setState({
                            visible:false
                        })
                    }}/> : ''}
                {/*外联客户回收*/}
                {this.state.recoveryVisible ? {
                        this.changeAssigner(value,2,true)
                    }}
                    onCancel={()=>{
                        this.setState({
                            recoveryVisible:false
                        })
                    }}/> : ''}
                {this.state.upLoadFileLoading ? : null}
             
        )
    }
}
export default Channel;