<template>
	<view>
		<u-modal :show="showModal" ref="uModal" :title="(editOrAdd === 'add' || editOrAdd === 'receptFormAdd') ? '新增' : '编辑'" :asyncClose="false" showCancelButton @cancel="closeDialog" cancelColor="#909399" :confirmText="'确定'" confirmColor="#2979ff" @confirm="confirm" @close="closeDialog" :closeOnClickOverlay="false">
            <u--text type="info" text="输入型号可查看价格趋势"></u--text>
            <view class="modal_wrap">
                <text @click="handleBrandClick" class="item" :class="info.dictLabel ? 'brand' : 'brand placeholder'">{{ info.dictLabel || '品牌' }}</text>
                <text class="divider">|</text>
                <u--input placeholder="型号" class="item" border="none" v-model="info.model" clearable @blur="handleModelBlur"></u--input>
                <text class="divider">|</text>
                <u--input class="code-input item" placeholder="编码" border="none" v-model="info.code" clearable></u--input>
            </view>
            <view class="img_wrap">
                <imgs-row-scroll v-if="info.imgsUrl.length > 0" :isShowDeleteIcon="true" @deleteImgInfo="getDeleteImgInfo" imgMode="aspectFill" :totalWidth="400" :images="info.imgsUrl" :previewEnabled="true" :imageWidth="150" :imageHeight="150"></imgs-row-scroll>
                <u-upload
                    @afterRead="afterRead"
                    name="3"
                    multiple
                    :maxCount="10"
                ></u-upload>
            </view>
            <u--input v-if="editOrAdd === 'edit'" class="price" placeholder="价格" border="bottom" v-model="info.price" clearable></u--input>
            <view class="charts_box" v-show="chartShow">
                 <u--text type="primary" :text="`最大价格：${Math.max(...maxPrice)}元`"></u--text>
                 <u--text type="warning" :text="`最小价格：${Math.min(...minPrice)}元`"></u--text>
                <qiun-data-charts type="line" :chartData="chartData" canvasId="trendChart" :opts="opts" :ontouch="true" tooltipFormat="tooltipFormatPrice"
                    width="700rpx" height="500rpx" backgroundColor="#ffffff" />
            </view>
        </u-modal>
        <brandList ref="brandListRef" @selectedBrand="handleSelectedBrand"></brandList>
	</view>
</template>

<script>
import imgsRowScroll from '@/components/imgs-row-scroll/index.vue'
import brandList from '@/components/brand-list/index.vue'
export default {
	name: 'AddInquiryDialog',
    components: {
        imgsRowScroll,
        brandList
    },
	props: {
        clueId: {
            type: String,
            default: ''
        },
		show: {
			type: Boolean,
			default: false
		},
        editOrAdd: {
            type: String,
            default: ''// edit 编辑(有价格), editForm 编辑询价单(无价格), add 新增询价单, receptFormAdd 新增接收询价单   线索页面：第一次点击是新增（不需要回显），status传1，第二次点击是无价格编辑status传1；接单中心:第一次点击是新增（需要回显）status传1，第二次点击是无价格编辑status传1；只有edit是有价格编辑status传2
        },
        editInfo: {
            type: Object,
            default: () => {}
        },
        type: {
            type: Number,
            default: 1
        },
	},
    emits: ['submitSuccess'],
	data() {
		return {
			showModal: false,
            info: {
                model:'',
                code:'',
                id:'',
                price:'',
                dictLabel:'',
                dictValue:'',
                imgsUrl:[]
            },
            rules: {
                brand: [
                    { required: true, message: '请输入品牌', trigger: 'blur' }
                ]
            },
            chartData:{},
            color:[],
            opts: {
                color: this.color,
                padding: [20, 10, 20, 0],
                dataLabel: true,
                dataPointShape: true,
                enableScroll: true,
                
                xAxis: {
                    disableGrid: true,
                    scrollShow: true,
                    itemCount: 10,
                    rotateLabel: true,
                    rotateAngle: 45,
                },
                yAxis: {
                    gridType: "dash",
                    dashLength: 7,
                },
                legend: {
                    show: false,
                    type: 'scroll',
                    orient: 'horizontal',
                    pageSize: 3,
                    pageIconSize: 12,
                    pageIconColor: '#666',
                    pageIconInactiveColor: '#ccc',
                    pageTextStyle: {
                        color: '#666',
                        fontSize: 12
                    },
                    bottom: 0
                },
                extra: {
                    line: {
                        type: "curve",
                        width: 3,
                        activeType: "hollow",
                        linearType: "custom",
                        onShadow: true,
                        animation: "horizontal"
                    },
                    tooltip:{
                        legendShow: true,
                        bgOpacity: 0.6
                    }
                }
            },
            chartShow: false,
            maxPrice: [],
            minPrice: [],
		}
	},
	watch: {
		show: {
			handler(newVal) {
				this.showModal = newVal;
			},
			immediate: true
		}
	},
	methods: {
        getChartData() {
            uni.$u.api.inquiryChart({
                model: this.info.model,
            }).then(res => {
                if (res.code == 200) {
                    const response = res.data
                    this.maxPrice = []
                    this.minPrice = []
                    // const response = [
                    //     {
                    //         model:'AAA',
                    //         list:[
                    //             {
                    //                 recycleTime: '2023-07-30',
                    //                 price: 300,
                    //             },
                    //             {
                    //                 recycleTime: '2023-07-31',
                    //                 price: 500,
                    //             },
                    //             {
                    //                 recycleTime: '2023-08-01',
                    //                 price: null,
                    //             },
                    //             {
                    //                 recycleTime: '2023-08-02',
                    //                 price: 200,
                    //             },
                    //             {
                    //                 recycleTime: '2023-08-03',
                    //                 price: 300,
                    //             }
                    //         ]
                    //     },
                    //     {
                    //         model:'BBB',
                    //         list:[
                    //             {
                    //                 recycleTime: '2023-08-01',
                    //                 price:400,
                    //             },
                    //             {
                    //                 recycleTime: '2023-08-02',
                    //                 price: 100,
                    //             },
                    //             {
                    //                 recycleTime: '2023-08-03',
                    //                 price: 200,
                    //             }
                    //         ]
                    //     },
                    //     {
                    //         model:'CCC',
                    //         list:[
                    //             {
                    //                 recycleTime: '2023-08-01',
                    //                 price: 500,
                    //             },
                    //             {
                    //                 recycleTime: '2023-08-02',
                    //                 price: 400,
                    //             },
                    //             {
                    //                 recycleTime: '2023-08-03',
                    //                 price: 600,
                    //             }
                    //         ]
                    //     }
                    // ]
                    this.color = []
                    const categories = []
                    const dateMap = {}
                    response.forEach(item => {
                        this.maxPrice.push(item.max)
                        this.minPrice.push(item.min)
                        item.list.forEach(i => {
                            if (!dateMap[i.recycleTime]) {
                                dateMap[i.recycleTime] = true
                                categories.push(i.recycleTime)
                            }
                        })
                    })
                    const series = response.map((item) => {
                        const color = this.getRandomColor()
                        this.color.push(color)
                        const data = categories.map(date => {
                            const itemData = item.list.find(i => i.recycleTime === date)
                            return itemData ? itemData.price : null
                        })
                        return {
                            name: item.model,
                            data: data,
                            setShadow: [
                                3,
                                8,
                                15,
                                color
                            ],
                        }
                    })
                    this.opts.color = this.color
                    const chartData = {
                        categories: categories,
                        series: series
                    }
                    this.chartData = JSON.parse(JSON.stringify(chartData))
                    this.chartShow = true
                }
            })
            
        },
        getRandomColor(){
            var letters = '0123456789ABCDEF';
            var color = '#';
            for (var i = 0; i < 6; i++) {
                color += letters[Math.floor(Math.random() * 16)];
            }
            return color;
        },
        // 编辑回显
        initData() {
            this.$nextTick(()=>{
                this.info = JSON.parse(JSON.stringify(this.editInfo))
                this.showModal = true;
                if(this.info.model && this.info.dictValue){
                    this.getChartData()
                }
            })
        },
        // 获取删除图片信息
        getDeleteImgInfo(info) {
            this.info.imgsUrl = info.newImages
        },
        handleBrandClick() {
            this.$refs.brandListRef.showBrandList();
        },
        handleSelectedBrand(info) {
            this.info.dictLabel = info.dictLabel
            this.info.dictValue = info.dictValue
        },
        // 上传图片
        afterRead(info) {
            info.file.forEach(item=>{
                uni.$u.api.uploadFile(item.url).then((res) => {
                    this.info.imgsUrl.push(res.data.url);
                    uni.$u.toast("文件上传成功");
                }).catch(() => {
                    uni.$u.toast("上传文件失败");
                })
            })
        },
        // 确认添加
        confirm() {
            if (!this.info.dictLabel || !this.info.dictValue) {
                uni.showToast({
                    title: '请选择品牌',
                    icon: 'none'
                })
                return
            }
            if (!this.info.model) {
                uni.showToast({
                    title: '请输入型号',
                    icon: 'none'
                })
                return
            }
            if (!this.info.code) {
                uni.showToast({
                    title: '请输入编码',
                    icon: 'none'
                })
                return
            }
            if(this.info.imgsUrl.length == 0){
                uni.showToast({
                    title: '请上传图片',
                    icon: 'none'
                })
                return
            }
            if(this.editOrAdd === 'edit' && !this.info.price){
                uni.showToast({
                    title: '请输入价格',
                    icon: 'none'
                })
                return
            }
            const data = {
                clueId: this.clueId,
                dictValue: this.info.dictValue,
                dictLabel: this.info.dictLabel,
                model: this.info.model,
                code: this.info.code,
                id: (this.editOrAdd === 'edit' || this.editOrAdd === 'editForm') ? this.info.id : '',
                price: this.editOrAdd === 'edit' ? this.info.price : '',
                imgsUrl:this.info.imgsUrl,
                status: this.editOrAdd === 'edit' ? '2' : '1',
                type: this.type
            }
            uni.$u.api.addInquiry(data).then(res => {
                if (res.code == 200) {
                    uni.showToast({
                        title: '添加成功',
                        icon: 'success'
                    })
                    this.closeDialog()
                    this.$emit('submitSuccess')
                }
            })
        },
        showDialog() {
            if (this.editOrAdd === 'edit' || this.editOrAdd === 'editForm' || this.editOrAdd === 'receptFormAdd') {
                this.initData();
            }else if(this.editOrAdd === 'add'){
                this.clearForm()
                this.showModal = true;
            }
        },
        clearForm() {
            this.info = {
                dictLabel:'',
                dictValue:'',
                model:'',
                code:'',
                id:'',
                price:'',
                imgsUrl:[]
            }
        },
        closeDialog() {
            this.showModal = false;
            this.chartShow = false
            this.chartData = {}
        },
        handleModelBlur() {
            if (this.info.model !== ''){
                this.getChartData()
            }
        },
	}
};
</script>

<style lang="scss" scoped>
    @import './index.scss'
</style>