<template>
    <div>
        <div style="display: flex; justify-content: flex-end; margin-bottom: 20px">
            <el-button @click="addData()">添加</el-button>
        </div>
        <el-table :data="tableData" border @sort-change="sortChange">
            <el-table-column label="时间" prop="saleTime" align="center" sortable="custom">
                <template slot-scope="scope">
                    <span v-if="!scope.row.vVisible">{{ scope.row.saleTime }}</span>
                    <el-date-picker
                        style="width: 100%"
                        v-else
                        v-model="scope.row.saleTime"
                        type="month"
                        value-format="yyyy-MM"
                        placeholder="选择日期时间"
                    >
                    </el-date-picker>
                </template>
            </el-table-column>
            <el-table-column label="地区" prop="saleArea" align="center" width="120px" sortable="custom">
                <template slot-scope="scope">
                    <span v-if="!scope.row.vVisible">{{ scope.row.saleArea }}</span>
                    <el-input v-else v-model="scope.row.saleArea" placeholder="请输入地区"></el-input>
                </template>
            </el-table-column>
            <el-table-column label="销售量/件" prop="saleCount" align="center" width="120px" sortable="custom">
                <template slot-scope="scope">
                    <span v-if="!scope.row.vVisible">{{ scope.row.saleCount }}</span>
                    <el-input v-else v-model="scope.row.saleCount" placeholder="请输入销售量/件"></el-input>
                </template>
            </el-table-column>
            <el-table-column label="销售额/万元" prop="saleMoney" align="center" width="120px" sortable="custom">
                <template slot-scope="scope">
                    <span v-if="!scope.row.vVisible">{{ scope.row.saleMoney }}</span>
                    <el-input v-else v-model="scope.row.saleMoney" placeholder="请输入销售额/万元"></el-input>
                </template>
            </el-table-column>
            <el-table-column label="许可参考值" prop="reference" align="center" width="120px">
                <template slot-scope="scope">
                    <span>{{row.licenseRate==0||row.licenseRate?(Number(scope.row.saleMoney) * Number(row.licenseRate)).toFixed(2):'' }}</span>
                </template>
            </el-table-column>
            <el-table-column label="自定义许可费" prop="customLicenseFee" align="center" width="200px">
                <template slot-scope="scope">
                    <span v-if="editId == scope.row.id"><el-input v-model="scope.row.customLicenseRates" placeholder="请输入自定义许可费率(许可费率介于0-1之间)" @blur="changeEditId(scope.row)" @change="inpBlur" autofocus=true></el-input></span>
                    <span v-else>{{ scope.row.customLicenseRate==0||scope.row.customLicenseRate?(Number(scope.row.saleMoney) * Number(scope.row.customLicenseRate)).toFixed(2):'' }} <span><i class="el-icon-edit" @click="editCustomLicenseRate(scope.row)"></i></span> </span>
                </template>
            </el-table-column>
            <el-table-column label="操作" width="160" align="center">
                <template slot-scope="scope">
                    <div class="special">
                        <span
                        v-if="!scope.row.vVisible"
                        class="items"
                        @click="edit(scope.row)"
                        >编辑</span
                        >
                        <span v-else class="items" @click="submit1(scope.row)">保存</span>
                        <span>&nbsp;|&nbsp;</span>
                        <span class="items" @click="deleteIt(scope.row)"  v-if="!scope.row.vVisible">删除</span>
                        <span v-else class="items" @click="getList">取消</span>
                    </div>
                </template>
            </el-table-column>
        </el-table>
        <div style="display: flex;justify-content: center;">
            <el-pagination
                background
                layout="total,prev, pager, next,jumper"
                :total="total"
                @current-change="handleCurrentChange"
                :current-page="queryParams.current" :page-size="queryParams.size">
            </el-pagination>
        </div>
        <el-dialog :title="title" :visible.sync="visible" width="1000px" append-to-body :close-on-click-modal="false" :before-close="close">
            <div>
                <el-form ref="form" :model="form" :rules="rules">
                    <el-form-item label="所属产品" prop="productName" v-if="form.productName">
                        <el-input v-model="form.productName" :disabled="true"></el-input>
                    </el-form-item>
                    <el-form-item label="时间" prop="saleTime">
                        <el-date-picker
                            style="width: 100%"
                            v-model="form.saleTime"
                            type="month"
                            value-format="yyyy-MM"
                            placeholder="选择日期时间"
                        >
                     </el-date-picker>
                    </el-form-item>
                    <el-form-item label="地区" prop="saleArea" >
                        <el-input v-model="form.saleArea"  placeholder="请输入地区"></el-input>
                    </el-form-item>
                    <el-form-item label="销售量/件" prop="saleCount">
                        <el-input v-model="form.saleCount" placeholder="请输入销售量"></el-input>
                    </el-form-item>
                    <el-form-item label="销售额/万元" prop="saleMoney">
                        <el-input v-model="form.saleMoney" placeholder="请输入销售额"></el-input>
                    </el-form-item>
                    <!-- <el-form-item label="许可参考值" prop="reference">
                        <el-input v-model="form.reference" placeholder="请输入销售额"></el-input>
                    </el-form-item> -->
                    <el-form-item label="自定义许可费率" prop="customLicenseRates">
                        <el-input v-model="form.customLicenseRates" placeholder="请输入自定义许可费率(许可费率介于0-1之间)" ></el-input>
                    </el-form-item>
                </el-form>
            </div> 
            <div slot="footer" class="dialog-footer" style="display: flex;justify-content: flex-end;">
                <el-button @click="close">取 消</el-button>
                <el-button type="primary" @click="submit" :loading="btnLoading">确定</el-button>
            </div> 
        </el-dialog>
    </div>
</template>
<script>
export default {
    props:['row'],
    data() {
        const customLicenseRateRule = (rule , value ,callback)=>{
            if(value){
                if (!isNaN(value)) {
                if (value>=0 && value<=1) {
                    this.form.customLicenseRates=value
                    this.form.customLicenseRate=this.form.customLicenseRates
                    callback()
                } else {
                    // if (value>1) {
                    //   this.categoryForm.licenseRate=1
                    // } else {
                    //   this.categoryForm.licenseRate=0
                    // }
                    callback(new Error('输入错误，自定义许可费率介于0-1之间'))
                }
                } else {
                // this.categoryForm.licenseRate=this.categoryForm.licenseRateA
                callback(new Error('输入错误，自定义许可费率介于0-1之间'))
                }
            }else{
                callback()
            }
        }
        return {
            editId:null,
            visible:false,
            btnLoading:false,
            title:'',
            form:{},
            queryParams:{
                size:10,
                current:1
            },
            total:0,
            tableData:[],
            rules:{
                saleTime:[ {required: true, message: '请选择日期', trigger: 'change' }],
                saleMoney:[{ required: true, message: '请输入销售额', trigger: 'blur' }],
                customLicenseRates:[{required: false, validator:customLicenseRateRule, trigger: 'blur' }]
            }
        }
    },
    watch:{
        row(val){
            this.getList2()
        },
    },
    mounted() {
        this.getList()
    },
    methods: {
        //编辑自定义许可费
        editCustomLicenseRate(row){
            this.$set(row,'customLicenseRates',row.customLicenseRate)
            this.editId = row.id
        },
        // 许可费率事件//优化
        inpBlur(row) {
            var val = row.customLicenseRates
            if (val) {
                if (!isNaN(val)) {
                    if (val >= 0 && val <= 1) {
                        row.customLicenseRate = val
                    } else {
                        if (val > 1) {
                            row.customLicenseRate = 1
                            row.customLicenseRates = 1
                        }
                        if (val < 0) {
                            row.customLicenseRate = 0
                            row.customLicenseRates = 0
                        }
                    }
                } else {
                    row.customLicenseRates = row.customLicenseRate?row.customLicenseRate:''
                }
            }
            
        },
        //失去焦点
        changeEditId(row){
            this.inpBlur(row)
            if(this.editId){
               this.$set(this,'editId',null)
            }
            this.update(row)
        },
        //重新查询
        getList2(){
            this.queryParams.current = 1
            this.getList()
        },
        //获取营销数据
        getList(){
            this.queryParams.productId = this.row.id
            this.$api.queryProductMarketData(this.queryParams).then(response=>{
                if(response.code == 200){
                    this.tableData = response.data.list
                    this.total = response.data.totalSizes
                }
            })
        },
        // 分页
        handleCurrentChange(val) {
            this.queryParams.current = val
            this.getList()
        },
        // 排序
        sortChange({ column, prop, order }) {
            if (!order) {
                return false
            }
            const o = {
                'descending': 'desc',
                'ascending': 'asc',
            }
            // console.log({ column, prop, order })
            this.queryParams.orderBy = prop
            this.queryParams.orderType = o[order]
            this.getList2()
        },
        //打开添加营销数据弹窗
        addData(){
            this.title = '添加'+this.row.productName+'营销数据'
            this.form = {
                productId : this.row.id,
                productName : this.row.productName,
                customLicenseRate : this.row.licenseRate,
                customLicenseRates : this.row.licenseRate
            }
            this.visible = true
        },
        //关闭弹窗
        close(){
            this.btnLoading = false
            this.visible = false
            this.$refs.form.resetFields()
            this.form = {}
        },
        //编辑销售量
        edit(row) {
            this.$set(row,'vVisible',!row.vVisible )
        },
        //保存
        submit1(row){
            var str = ''
            if(!row.saleTime){
                str = str + '时间'
            }
            if(!row.saleMoney){
                if(str.length>0){
                    str = str + '和销售额'
                }else{
                    str = str + '销售额'
                }
            }
            if(str.length>0){
                this.$alert(str+'不可为空', '提示', {
                    confirmButtonText: '确定',
                    callback: action => {
                    }
                });
                return false
            }
            this.update(row)
        },
        //更新营销数据
        update(row){
            row.productId = this.row.id
            this.$api.updateProductMarketData(row).then(response=>{
                if(response.code == 200){
                    this.$message.success('修改成功！')
                    row.vVisible = false
                }else{
                    this.$message.error('修改失败！')
                }
            }).catch(e=>{
                this.$message.error('修改失败！')
            })
        },
        //删除营销数据
        deleteIt(row){
            this.$confirm('确认删除本条数据吗？', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning'
            }).then(() => {
                this.$api.deleteProductMarketData({id:row.id}).then(response=>{
                    if(response.code == 200){
                        this.$message.success('删除成功！')
                        if(this.tableData.length==1&&this.queryParams.current!=1){
                            this.queryParams.current -= 1
                        }
                        this.getList()
                    }else{
                        this.$message.error('删除失败！')
                    }
                }).catch(e=>{
                    this.$message.error('删除失败！')
                })
            })
           
        },
        //确认添加营销数据
        submit(){
            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.btnLoading = true
                    this.$api.addNewProductMarketData(this.form).then(response=>{
                        if(response.code == 200){
                            this.$message.success('添加成功！')
                            this.getList()
                            this.close()
                        }else{
                            this.$message.error('添加失败！')
                            this.btnLoading = false
                        }
                    }).catch(e=>{
                        this.$message.error('添加失败！')
                        this.btnLoading = false
                    })
                } else {
                    // console.log('error submit!!');
                    return false;
                }
            });
        }
    },
}
</script>
<style lang="scss" scoped>
.items{
    cursor: pointer;
}
</style>