<template>
    <view>
        <van-popup position="bottom" :show="visible" round @close="close" closable>
            <view class="popup-container">
                <view class="title">事件派单</view>
                <scroll-view scroll-y class="popup-content">
                    <view class="card">
                        <view class="items">
                            <view class="label">事件类型：</view>
                            <view class="value">{{ detail.parentCategoryName }}-{{ detail.categoryName }}</view>
                        </view>
                        <view class="items">
                            <view class="label">接收时间：</view>
                            <view class="value">{{ detail.happenTime }}</view>
                        </view>
                        <view class="items">
                            <view class="label">发生地点：</view>
                            <view class="value">{{ detail.address }}</view>
                        </view>
                        <view class="items">
                            <view class="label">事件描述：</view>
                            <view class="value">
                                {{ detail.eventContent }}
                            </view>
                        </view>

                        <view class="items">
                            <view class="label">处理方式：</view>
                            <view class="value">
                                <van-radio-group :value="operationType" @change="operationTypeChange">
                                    <view class="flex">
                                        <van-radio name="5">指派</van-radio>
                                        <view style="width: 40rpx"></view>
                                        <!-- <van-radio name="">转服务</van-radio> -->
                                    </view>
                                </van-radio-group>
                            </view>
                        </view>
                        <view class="items" @tap="onOpen1">
                            <view class="label label-width">事件分类：</view>
                            <view :class="'value flex ' + (category ? '' : 'gray')">
                                {{ category ? category : '请选择' }}
                                <van-icon name="arrow" />
                            </view>
                        </view>
                        <view class="items" @tap="onOpen2">
                            <view class="label label-width">处理部门：</view>
                            <view :class="'value flex ' + (orgName ? '' : 'gray')">
                                {{ orgName ? orgName : '请选择' }}
                                <van-icon name="arrow" />
                            </view>
                        </view>
                        <view class="items">
                            <view class="label">转办意见：</view>
                        </view>
                        <view class="items">
                            <textarea class="textarea" v-model="form.content" @input="setContent" placeholder-class="textarea-placeholder" placeholder="请填写转办意见。" />
                        </view>
                    </view>
                    <view class="card">
                        <view class="items">
                            <view class="label">图片/附件：</view>
                        </view>
                        <view class="items">
                            <van-uploader :file-list="fileList" @delete="deleteFile" max-count="4" @after-read="afterRead" />
                        </view>
                    </view>

                    <view class="card">
                        <view class="items" @tap="openCalendar1">
                            <view class="label label-width">办结时限：</view>
                            <view :class="'value flex ' + (form.timeLimit ? '' : 'gray')">
                                {{ form.timeLimit ? form.timeLimit : '请选择' }}
                                <van-icon name="arrow" />
                            </view>
                        </view>
                    </view>
                </scroll-view>

                <view class="bottom-btn">
                    <view class="btn btn-gray" @tap="close">取消</view>
                    <view class="btn btn-blue" @tap="sure">确定</view>
                </view>
            </view>
        </van-popup>
        <wux-calendar id="wux-calendar" />
        <van-popup :show="visible1" round position="bottom">
            <van-cascader v-if="visible1" :default-value="value1" title="事件分类" :options="casOptions" @close="onClose1" @finish="onConfirm1" :field-names="catField" />
        </van-popup>
        <van-popup :show="visible2" round position="bottom">
            <van-cascader v-if="visible2" :default-value="value2" title="处理部门" :options="orgOptions" @close="onClose2" @finish="onConfirm2" :field-names="orgField" />
        </van-popup>

        <van-calendar :show="showDate" @close="onCloseDate" @confirm="onConfirmDate" />
    </view>
</template>

<script>
import { agencygridtree, getCategoryTree, icEvent12345, icEventOld, icEventOldReply } from '../../utils/statisticsApi';
const config = require('../../utils/config');
export default {
    data() {
        return {
            value: 666,

            detail: {
                parentCategoryName: '',
                categoryName: '',
                happenTime: '',
                address: '',
                eventContent: ''
            },

            agencyId: '',
            id: '',
            loading: true,
            fileList: [],
            timeLimit: [],
            operationType: ['5'],

            form: {
                operationType: '5',

                //处理方式[0:已回复 5、指派  6、完成并回复]
                content: '',

                //转办意见
                timeLimit: '',

                //办结时限
                categoryId: '',

                //事件分类
                deptId: '',

                //指派部门
                deptName: '',

                categoryList: [],

                //附件
                files: [],

                orgType: ''
            },

            orgOptions: [],
            casOptions: [],
            visible1: false,
            visible2: false,

            catField: {
                text: 'categoryName',
                value: 'id',
                children: 'children'
            },

            orgField: {
                text: 'agencyName',
                value: 'agencyId',
                children: 'subAgencyList'
            },

            orgName: '',
            category: '',
            showDate: false,
            value1: '',
            value2: ''
        };
    },
    props: {
        visible: {
            type: Boolean,
            default: false
        },
        eventId: {
            type: String,
            default: ''
        },
        is12345: {
            type: Boolean,
            default: true
        }
    },
    mounted() {
        // 处理小程序 ready 生命周期
        this.$nextTick(() => this.ready());
    },
    methods: {
        ready: function () {},

        operationTypeChange(e) {
            console.log(e.detail);
            this.setData({
                operationType: e.detail,
                'form.operationType': e.detail[0]
            });
        },

        onOpen1() {
            this.setData({
                visible1: true
            });
        },

        onClose1() {
            this.setData({
                visible1: false
            });
            console.log('onClose1');
        },

        onConfirm1(e) {
            console.log('onConfirm1', e.detail);
            let data = e.detail;
            let params = data.selectedOptions[data.selectedOptions.length - 1];
            this.setData({
                'form.categoryId': params.id,
                'form.categoryList': {
                    ...params,
                    children: null
                },
                visible1: false
            });
            this.setData({
                category: data.selectedOptions.map((item) => item.categoryName).join('/')
            });
        },

        setContent(e) {
            console.log(e, 'eee');
            this.setData({
                'form.content': e.detail.value
            });
        },

        onOpen2() {
            this.setData({
                visible2: true
            });
        },

        onClose2() {
            this.setData({
                visible2: false
            });
            console.log('onClose2');
        },

        onConfirm2(e) {
            let data = e.detail;
            let params = data.selectedOptions[data.selectedOptions.length - 1];
            this.setData({
                'form.deptId': params.agencyId,
                'form.deptName': params.agencyName,
                'form.orgType': params.level,
                visible2: false
            });
            this.setData({
                orgName: data.selectedOptions.map((item) => item.agencyName).join('/')
            });
        },

        getData() {
            if (this.is12345) {
                icEvent12345({
                    icEventId: this.id
                }).then((res) => {
                    this.getDetail(res.data);
                });
            } else {
                icEventOld({
                    icEventId: this.id
                }).then((res) => {
                    this.getDetail(res.data);
                });
            }
        },

        getDetail(data) {
            this.setData({
                detail: data,
                agencyId: data.agencyId
            });
            this.getOrgTreeList();
            this.getCategoryList();
        },

        getOrgTreeList() {
            let params = {
                agencyId: this.agencyId,
                purpose: 'query'
            };
            agencygridtree(params).then((res) => {
                this.setData({
                    orgOptions: this.deleteChildren(res.data.subAgencyList, 'subAgencyList')
                });
            });
        },

        //重构树，去除网格
        deepTree(arr, children) {
            if (Array.isArray(arr) && arr.length > 0) {
                return arr.map((item) => {
                    return {
                        ...item,
                        [children]: (item[children] && item[children].length > 0 && this.deepTree(item[children], children)) || null
                    };
                });
            }
        },

        getCategoryList() {
            let params = {};
            getCategoryTree(params).then((res) => {
                let treeDataNew = this.deepTree(res.data, 'children');
                console.log(treeDataNew, 'treeDataNew');
                this.setData({
                    casOptions: this.deleteChildren(treeDataNew, 'children')
                });
            });
        },

        deleteChildren(node, key) {
            node.forEach((item) => {
                if (key in item && !item[key]) {
                    delete item[key];
                } else if (key in item && item[key].length) {
                    this.deleteChildren(item[key], key);
                }
            });
            return node;
        },

        close() {
            this.$emit('close');
        },

        openCalendar1() {
            this.setData({
                showDate: true
            });
        },

        onCloseDate() {
            this.setData({
                showDate: false
            });
        },

        formatDate(date) {
            date = new Date(date);
            return `${date.getFullYear()}-${date.getMonth() + 1 > 10 ? date.getMonth() + 1 : '0' + (date.getMonth() + 1)}-${
                date.getDate() > 10 ? date.getDate() : '0' + date.getDate()
            }`;
        },

        onConfirmDate(event) {
            console.log(event);
            const date = event.detail;
            this.setData({
                showDate: false,
                'form.timeLimit': `${this.formatDate(date)} 00:00:00`
            });
        },

        afterRead(event) {
            const { file } = event.detail;
            // 当设置 mutiple 为 true 时, file 为数组格式，否则为对象格式
            uni.uploadFile({
                url: `${config.BASEURL()}oss/file/uploadvariedfile`,
                name: 'file',
                header: {
                    'Content-type': 'application/json;charset=UTF-8',
                    Authorization: uni.getStorageSync('token')
                },
                filePath: file.url,
                success: (res) => {
                    let data = JSON.parse(res.data);
                    const fileList = this.fileList;
                    fileList.push({
                        ...file,
                        url: data.data.url
                    });
                    console.log(fileList);
                    this.setData({
                        fileList
                    });
                }
            });
        },

        deleteFile(e) {
            console.log(e);
            let index = e.detail.index;
            let fileList = this.fileList;
            fileList.splice(index, 1);
            this.setData({
                fileList
            });
        },

        sure() {
            let params = {
                ...this.form,
                files: this.fileList,
                icEventId: this.id,
                status: 'processing'
                // timeLimit: this.data.value1 && this.data.value1.length ? this.data.value1[0] : ""
            };

            icEventOldReply(params).then((res) => {
                uni.showToast({
                    icon: 'success',
                    title: '操作成功'
                });
                this.close();
            });
            console.log(params);
        }
    },
    created: function () {},
    watch: {
        eventId: {
            handler: function (val) {
                console.log(val);
                this.setData({
                    id: val
                });
                this.getData();
            },

            immediate: true
        }
    }
};
</script>
<style>
.wux-popup__content {
    background: none !important;
}

.popup-container {
    padding: 32rpx 20rpx 50rpx;
    background: linear-gradient(180deg, #dbeeff 0%, #f4faff 100%);
    border-radius: 30rpx;
}

.title {
    font-size: 34rpx;
    font-weight: bold;
    color: #333333;
    display: flex;
    align-items: center;
    margin-bottom: 39rpx;
    position: relative;
}

.title:before {
    content: '';
    display: block;
    width: 10rpx;
    height: 28rpx;
    background: #3a80e7;
    border-radius: 4rpx;
    margin-right: 20rpx;
}

.popup-content {
    max-height: 60vh;
}
.popup-content .card {
    border-radius: 20px;
    padding: 30rpx;
    box-sizing: border-box;
    background: #fff;
    margin-bottom: 30rpx;
}
.items {
    display: flex;
    align-items: flex-start;
    text-align: left;
    font-size: 32rpx;
    font-weight: 500;
    color: #333333;
    margin-bottom: 29rpx;
    position: relative;
}

.items .label {
    white-space: nowrap;
    width: 160rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
}

.items .value {
    width: calc(100% - 160rpx);
    overflow: hidden;
    text-overflow: ellipsis;
    display: -webkit-box;
    -webkit-line-clamp: 3;
    -webkit-box-orient: vertical;
    max-height: 144rpx;
}

.tel {
    width: 126rpx;
    height: 62rpx;
    position: absolute;
    top: calc(50% - 31rpx);
    right: 0;
}
.textarea {
    width: 100%;
    height: 340rpx;
    background: #f7f7f7;
    border-radius: 20rpx;
    padding: 27rpx 31rpx;
}
.textarea-placeholder {
    font-size: 32rpx;
    font-weight: 500;
    color: #c1c1c1;
    line-height: 42rpx;
}

.bottom-btn {
    background: none;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 20rpx 99rpx 20rpx;
    /*padding-bottom: calc(env(safe-area-inset-bottom) + 10rpx);*/
    width: 100%;
    box-sizing: border-box;
    z-index: 999;
    position: static;
}
.btn {
    width: 240rpx;
    height: 76rpx;
    border-radius: 38rpx;
    color: #fff;
    display: flex;
    align-items: center;
    justify-content: center;
    text-align: center;
    font-size: 32rpx;
    font-weight: bold;
}
.btn-blue {
    background: linear-gradient(87deg, #81b5fb 0%, #3e92ff 100%);
}
.btn-gray {
    background: #d9d9d9;
}

.gray {
    color: #999;
}
.text-right {
    text-align: right;
}
.flex {
    display: flex !important;
    justify-content: flex-end;
    align-items: center;
}

.label-width {
    min-width: 160rpx;
}
</style>
