import React,{ Component } from 'react';
import {
    AutoComplete,
    Button,
    DatePicker,
    Input,
    message,
    Modal,
    Select,
    Spin,
    Table,
    Tabs,
    Tag,
    Form,
    Upload, Tooltip
} from "antd";
import {ShowModal,splitUrl,getClockState} from "@/tools";
import {clockState} from "@/dataDic";
import {ChooseList} from "../../order/orderNew/chooseList";
import $ from "jquery/src/ajax";
import './index.less';
import moment from "moment";
import ImgList from "../../../common/imgList";


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

class DetailedList extends Component{
    constructor(props) {
        super(props);
        this.state={
            pageNo:1,
            loading:false,
            changeList:[],
            annexUrlArr:[],
            photoUrlArr:[],
            imgListVisible:false,
            columns: [
                {
                    title: "编号",
                    dataIndex: "key",
                    key: "key",
                },
                {
                    title: "客户名称",
                    dataIndex: "nickname",
                    key: "nickname",
                    width: 150,
                    render: (text) => {
                        return (
                            <Tooltip title={text}>
                                <div style={{
                                    maxWidth:'150px',
                                    overflow:'hidden',
                                    textOverflow: "ellipsis",
                                    whiteSpace:'nowrap',
                                }}>{text}</div>
                            </Tooltip>
                        )
                    },
                },
                {
                    title: "公出申请人",
                    dataIndex: "aname",
                    key: "aname",
                },
                {
                    title: "申请时间",
                    dataIndex: "createTimes",
                    key: "createTimes",
                },
                {
                    title: "公出时间",
                    dataIndex: "releaseStarts",
                    key: "releaseStarts",
                    render: (text, record) => (
                        text+'至'+record.releaseEnds
                    )
                },
                {
                    title: "公出地点",
                    dataIndex: "userName",
                    key: "userName",
                    width: 120,
                    render: (text) => {
                        return (
                            <Tooltip title={text}>
                                <div style={{
                                    maxWidth:'120px',
                                    overflow:'hidden',
                                    textOverflow: "ellipsis",
                                    whiteSpace:'nowrap',
                                }}>{text}</div>
                            </Tooltip>
                        )
                    },
                },
                {
                    title: "公出时长(时)",
                    dataIndex: "duration",
                    key: "duration",
                },
                {
                    title: "打卡时间",
                    dataIndex: "clockInTimes",
                    key: "clockInTimes",
                },
                {
                    title: "审核状态",
                    dataIndex: "status",
                    key: "status",
                    render: (text) => (
                        <Tag color={getClockState(text).color}>{getClockState(text).title}</Tag>
                    )
                },
                {
                    title: "打卡状态",
                    dataIndex: "clockIn",
                    key: "clockIn",
                    render: (text) => (
                        text === 1 ? '已打卡' :
                            text === 0 ? '未打卡' : ''
                    )
                },
                {
                    title: "操作",
                    dataIndex: "annexUrl",
                    key: "annexUrl",
                    render: (text,record) => (
                        <div>
                            <Button
                                style={{marginRight:'15px'}}
                                type={"primary"}
                                onClick={(e) => {
                                    e.stopPropagation();
                                    let arr1 = text || [];
                                    let arr2 = record.photoUrl || [];
                                    this.setState({
                                        annexUrlArr:splitUrl(arr1, ",", globalConfig.avatarHost + "/upload"),
                                        photoUrlArr:splitUrl(arr2, ",", globalConfig.avatarHost + "/upload"),
                                    },()=>{
                                        this.setState({
                                            imgListVisible:true
                                        })
                                    })
                                }}
                            >
                                查看公出附件
                            </Button>
                        </div>
                    )
                },
            ],
            pagination: {
                defaultCurrent: 1,
                defaultPageSize: 10,
                showQuickJumper: true,
                pageSize: 10,
                onChange: function(page) {
                    this.loadData(page);
                }.bind(this),
                showTotal: function(total) {
                    return "共" + total + "条数据";
                }
            },
            dataSource: [],

            releaseDate:[],
            status:props.status,
            clockIn:props.clockIn,
            theTypes:props.aid,
            theCustomerTypes:undefined,
        }
        this.loadData = this.loadData.bind(this);
        this.resetAll = this.resetAll.bind(this);
        this.changeList = this.changeList.bind(this);
        this.selectSuperId = this.selectSuperId.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.getCustomer = this.getCustomer.bind(this);
        this.selectCustomerAuto = this.selectCustomerAuto.bind(this);
        this.httpCustomerChange = this.httpCustomerChange.bind(this);
        this.blurCustomerChange = this.blurCustomerChange.bind(this);
        this.exportExec = this.exportExec.bind(this);
    }

    //获取上级组织
    selectSuperId() {
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/organization/selectSuperId",
            data:{},
            success: function (data) {
                let theArr = [];
                if (data.error && data.error.length === 0) {
                    for(let i=0;i<data.data.length;i++){
                        let theData = data.data[i];
                        theArr.push(
                            <Select.Option value={theData.id} key={theData.id}>{theData.name}</Select.Option>
                        );
                    };
                    this.setState({
                        contactsOption: theArr,
                    });
                }else{
                    message.warning(data.error[0].message);
                }
            }.bind(this),
        }).always(function () {
            this.setState({
                loading: false
            });
        }.bind(this));
    }

    changeList(arr) {
        const newArr = [];
        this.state.columns.forEach(item => {
            arr.forEach(val => {
                if (val === item.title) {
                    newArr.push(item);
                }
            });
        });
        this.setState({
            changeList: newArr
        });
    }

    loadData(pageNo) {
        this.setState({
            loading:true
        })
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/release/publicReleaseDtails",
            data: {
                pageNo: pageNo || 1,
                pageSize: this.state.pagination.pageSize,
                releaseStart:this.state.releaseDate[0] || undefined,
                releaseEnd:this.state.releaseDate[1] || undefined,
                aid:this.state.theTypes,
                uid:this.state.theCustomerTypes,
                status:this.state.status,
                clockIn:this.state.clockIn,
            },
            success: function(data) {
                ShowModal(this);
                let theArr = [];
                this.setState({
                    loading:false
                })
                if (data.error && data.error.length === 0) {
                    for (let i = 0; i < data.data.list.length; i++) {
                        let thisdata = data.data.list[i];
                        thisdata.key=(data.data.pageNo - 1) * data.data.pageSize + i + 1;
                        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({
                        dataSource: theArr,
                        pagination: this.state.pagination,
                        pageNo:data.data.pageNo
                    });
                }else{
                    message.warning(data.error[0].message);
                }
            }.bind(this)
        }).always(
            function() {
                this.setState({
                    loading: false
                });
            }.bind(this)
        );
    }

    resetAll() {
        this.setState({
            releaseDate:[],
            theCustomerTypes:undefined,
            status:this.props.status,
            clockIn:this.props.clockIn,
            auto:'',
            customer:''
        },()=>{
            this.loadData();
        })
    }

    supervisor(e) {
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/customer/listAdminByName",
            data: {
                adminName: e,
            },
            success: function (data) {
                if (data.error && data.error.length === 0) {
                    this.setState({
                        customerArr: data.data,
                    });
                }else{
                    message.warning(data.error[0].message);
                }
            }.bind(this),
        }).always(
            function () {

            }.bind(this)
        );
    }

    httpChange(e) {
        if (e.length >= 1) {
            this.supervisor(e);
        }
        this.setState({
            auto: e,
        });
    }

    selectAuto(value, options) {
        this.setState({
            auto: value,
        });
    }

    httpCustomerChange(e) {
        if (e.length >= 1) {
            this.getCustomer(e);
        }
        this.setState({
            customer: e,
        });
    }

    selectCustomerAuto(value, options) {
        this.setState({
            customer: value,
        });
    }

    getCustomer(e) {
        $.ajax({
            method: "get",
            dataType: "json",
            crossDomain: false,
            url: globalConfig.context + "/api/admin/customer/getUserByName",
            data: {
                name: e,
            },
            success: function (data) {
                if (data.error && data.error.length === 0) {
                    this.setState({
                        customerList: data.data,
                    });
                }else{
                    message.warning(data.error[0].message);
                }
            }.bind(this),
        }).always(
            function () {

            }.bind(this)
        );
    }

    blurCustomerChange(e) {
        let theType = "";
        let contactLists = this.state.customerList || [];
        if (e) {
            contactLists.map(function (item) {
                if (item.name == e.toString()) {
                    theType = item.id;
                }
            });
        }
        this.setState({
            theCustomerTypes: theType,
        });
    }

    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,
        });
    }

    componentWillMount() {
        this.loadData();
        this.selectSuperId();
    }

    exportExec(){
        let data = {
            releaseStart:this.state.releaseDate[0],
            releaseEnd:this.state.releaseDate[1],
            aid:this.state.theTypes,
            uid:this.state.theCustomerTypes,
            status:this.state.status,
            clockIn:this.state.clockIn,
        };
        for(let i of Object.keys(data)){
            if(i === 'status' || i === 'clockIn'){
                if(isNaN(parseInt(data[i]))){
                    delete data[i]
                }
            }else if(!data[i]){
                delete data[i]
            }

        }
        window.location.href =
            globalConfig.context +
            "/api/admin/release/publicReleaseDtails/export?" +
            $.param(data);
    }

    render() {
        const dataSources = this.state.customerArr || [];
        const options = dataSources.map((group) => (
            <Select.Option key={group.id} value={group.name}>
                {group.name}
            </Select.Option>
        ));
        const customerList = this.state.customerList || [];
        const customerOptions = customerList.map((group) => (
            <Select.Option key={group.id} value={group.name}>
                {group.name}
            </Select.Option>
        ));
        return (
            <div>
                <Modal
                    maskClosable={false}
                    visible={this.props.visible}
                    onOk={this.props.onCancel}
                    onCancel={this.props.onCancel}
                    width='1200px'
                    title='公出详细列表'
                    footer=''
                    className="admin-desc-content">
                    <div className="user-content">
                        <Tabs defaultActiveKey="1" className="test">
                            <TabPane tab="搜索" key="1">
                                <div className="user-search" style={{
                                    marginTop:'10px',
                                    marginLeft:'10px',
                                    marginRight:'10px'
                                }}>
                                       <span style={{ marginRight: "10px" }}>
                                            <AutoComplete
                                                className="certain-category-search"
                                                dropdownClassName="certain-category-search-dropdown"
                                                dropdownMatchSelectWidth={false}
                                                dropdownStyle={{ width: 120 }}
                                                style={{ width: "120px" }}
                                                dataSource={customerOptions}
                                                placeholder='输入客户名称'
                                                value={this.state.customer}
                                                onChange={this.httpCustomerChange}
                                                filterOption={true}
                                                onBlur={this.blurCustomerChange}
                                                onSelect={this.selectCustomerAuto}
                                            >
                                                <Input />
                                            </AutoComplete>
                                        </span>
                                    <span style={{ marginRight: "10px" }}>
                                            <Select
                                                placeholder="请选择审核状态"
                                                style={{ width:200,marginLeft:10}}
                                                value={this.state.status}
                                                onChange={(e) => { this.setState({ status: e }) }}>
                                                {
                                                    clockState.map((v,k) => (
                                                        <Select.Option key={k} value={v.id} >{v.title}</Select.Option>
                                                    ))
                                                }
                                            </Select>
                                    </span>
                                    <span style={{ marginRight: "10px" }}>
                                            <Select
                                                placeholder="请选择打卡状态"
                                                style={{ width:200,marginLeft:10}}
                                                value={this.state.clockIn}
                                                onChange={(e) => { this.setState({ clockIn: e }) }}>
                                                <Select.Option value={1} >已打卡</Select.Option>
                                                <Select.Option value={0} >未打卡</Select.Option>
                                            </Select>
                                    </span>
                                    <span style={{ marginRight: "10px" }}>
                                            <AutoComplete
                                                className="certain-category-search"
                                                dropdownClassName="certain-category-search-dropdown"
                                                dropdownMatchSelectWidth={false}
                                                dropdownStyle={{ width: 120 }}
                                                style={{ width: "120px" }}
                                                dataSource={options}
                                                placeholder='输入公出申请人'
                                                value={this.state.auto}
                                                onChange={this.httpChange}
                                                filterOption={true}
                                                onBlur={this.blurChange}
                                                onSelect={this.selectAuto}
                                            >
                                                <Input />
                                            </AutoComplete>
                                        </span>
                                    <span style={{ marginRight: "10px" }}>
                                            <span style={{marginRight:'5px',marginBottom:'10px'}}>公出时间 :</span>
                                            <RangePicker
                                                style={{marginRight:'10px',marginBottom:'10px'}}
                                                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 });
                                                }}
                                            />
                                        </span>
                                    <Button type="primary" onClick={()=>{
                                        this.loadData();
                                    }} style={{marginRight:'10px',marginBottom:'10px'}}>搜索</Button>
                                    <Button onClick={this.resetAll} style={{marginRight:'10px',marginBottom:'10px'}}>重置</Button>
                                </div>
                            </TabPane>
                            <TabPane tab="更改表格显示数据" key="2">
                                <div style={{ marginLeft: 10 }}>
                                    <Spin spinning={this.state.loading}>
                                        <ChooseList
                                            columns={this.state.columns}
                                            changeFn={this.changeList}
                                            changeList={this.state.changeList}
                                            top={55}
                                            margin={11}
                                        />
                                    </Spin>
                                </div>
                            </TabPane>
                            <TabPane tab="导出" key="3">
                                <div style={{ float: "left" }}>
                                    <Button onClick={this.exportExec} style={{ margin: 10 }}>导出excel</Button>
                                </div>
                            </TabPane>
                        </Tabs>
                        <div className="patent-table">
                            <Spin spinning={this.state.loading}>
                                <Table
                                    bordered
                                    size="middle"
                                    scroll={{ x: 800, y: 0 }}
                                    columns={
                                        this.state.changeList.length > 0
                                            ? this.state.changeList
                                            : this.state.columns
                                    }
                                    dataSource={this.state.dataSource}
                                    pagination={this.state.pagination}
                                />
                            </Spin>
                        </div>
                    </div>
                </Modal>
                {this.state.imgListVisible ? <Modal
                    maskClosable={false}
                    visible={this.state.imgListVisible}
                    onOk={()=>{this.setState({
                        imgListVisible:false
                    })}}
                    onCancel={()=>{this.setState({
                        imgListVisible:false
                    })}}
                    width='500px'
                    title='图片'
                    footer=''>
                    <div>
                        <div>申请附件</div>
                        <ImgList fileList={this.state.annexUrlArr} domId='publicStatistics'/>
                        <div style={{paddingTop:'35px'}}>打卡照片</div>
                        <ImgList fileList={this.state.photoUrlArr} domId='publicStatistics1'/>
                    </div>
                </Modal> : null}
            </div>


        )
    }
}

export default DetailedList;
