<template>
    <div v-loading="loading">
        <div class="white-box">
            <div class="filter-box">
                <filter-user :filter-types="filterTypes" @select-value="handleFilterUser"></filter-user>
            </div>
            <el-table class="table-box" ref="multipleTable" :data="tableData" stripe style="width: 100%;" :height="tool.getTableHeight()" @selection-change="handleSelectionChange">
                 <el-table-column fixed type="selection" width="55" v-if="tableHeaders" :selectable="checkSelectable"></el-table-column>
                <el-table-column v-for="(tableHeader, key) in tableHeaders" :key="key" :label="tableHeader.header" :width="tableHeader.other.width ? tableHeader.other.width : ''" :prop="tableHeader.other.prop ? tableHeader.other.prop : null">
                    <template slot-scope="scope">
                        <template v-if="scope.row[tableHeader.index].other.tag" >
                            <el-tag :type="scope.row[tableHeader.index].other.tag.type ? scope.row[tableHeader.index].other.tag.type : null" :size="scope.row[tableHeader.index].other.tag.size ? scope.row[tableHeader.index].other.tag.size : null" :class="scope.row[tableHeader.index].other.tag.class ? scope.row[tableHeader.index].other.tag.class : null" >{{scope.row[tableHeader.index].value}}</el-tag>
                        </template>
                        <template v-else>
                            <div v-html="scope.row[tableHeader.index].value"></div>
                        </template>
                    </template>
                </el-table-column>
                <el-table-column fixed="right" label="operation" width="180"><!-- 操作 -->
                    <template slot-scope="scope">
                        <el-dropdown size="small" trigger="click" v-if="permission.hasPermission(`shop/goods-edit`) || permission.hasPermission(`shop/goods-delete`)">
                            <el-button type="primary" size="small" @click.stop="">
                                Operate on this data<!-- 操作该数据 --><i class="el-icon-arrow-down el-icon--right"></i>
                            </el-button>
                            <el-dropdown-menu slot="dropdown">
                                <el-dropdown-item command="goods-edit" @click.native="handleEditShow(scope.row)">Edit<!-- 修改数据 --> </el-dropdown-item>
                                <el-dropdown-item command="del" @click.native="handleDel(scope.row.ID)"
                                                  v-show="permission.hasPermission(`shop/goods-delete`)">Delete<!-- 删除数据 -->
                                </el-dropdown-item>
                                <el-dropdown-item command="goods-edit" @click.native="handleGoodUp(scope.row.ID)">On sale<!-- 商品上架 --> </el-dropdown-item>
                                 <el-dropdown-item command="goods-edit" @click.native="handleGoodDown(scope.row.ID)">Sold out<!-- 商品下架 --> </el-dropdown-item>
                            </el-dropdown-menu>
                        </el-dropdown>
                    </template>
                </el-table-column>
             <!--   <el-table-column label="操作">
                    <template slot-scope="scope">
                        <el-button type="success" size="small" @click="handleGroupManage(scope.row)" >
                            状态管理
                        </el-button>
                    </template></el-table-column>-->

            </el-table>
            <div class="white-box-footer">

               <!-- <el-dropdown size="small" trigger="click">
                    <el-button type="primary" size="small">
                        所选数据<i class="el-icon-arrow-down el-icon&#45;&#45;right"></i>
                    </el-button>
                    <el-dropdown-menu slot="dropdown">
                        <el-dropdown-item command="delete" @click.native="handleMuliDel()">上架</el-dropdown-item>
                    </el-dropdown-menu>
                </el-dropdown>-->
                <el-button type="primary" size="small" @click="handlestate" icon="el-icon-plus"
                           v-if="permission.hasPermission(`shop/goods-add`)"><!-- 商品添加 -->Products add
                </el-button>

                <el-button type="success" size="small" @click="handleExport" v-show="permission.hasPermission(`shop/goods-list-export`)">Export Excel</el-button>
                <!-- <el-button-group>
                    <el-button type="success" size="mini" @click.native="handleup(scope.row.ID)">上架</el-button>
                    <el-button type="danger" size="mini">下架</el-button>
                </el-button-group> -->
                <pagination :total="totalCount" :page_size="pageSize" @size-change="handleSizeChange" @current-change="handleCurrentChange"></pagination>
            </div>
        </div>
        <el-dialog title="Edit Products" :visible.sync="dialogEditFormVisible"><!-- 修改商品 -->
            <el-form :model="form" label-width="250px" class="form-dialog" v-loading="dialogEditLoading">


                    <el-form-item label="Products Name"><!-- 商品名称 -->
                        <el-input v-model="form.goodsName"></el-input>
                    </el-form-item>
                    <!-- <el-form-item label="商品来源">
                        <el-select v-model="form.type">
                            <el-option v-for="(item,index) in goodsType" :key="index" :label="item.name"
                                       :value="index"></el-option>
                        </el-select>
                    </el-form-item> -->
                    <el-form-item label="Member discount"><!-- 会员折扣 -->
                        <el-input v-model="form.sellDiscount"></el-input>
                    </el-form-item>
                    <el-form-item label="Product type"><!-- 商品类型 -->
                        <el-checkbox  v-for="(value,index) in GiftTypeArr" v-model="value.checked" :key="index" >{{value.name}}</el-checkbox>
                    </el-form-item>
                    <!-- <el-form-item label="复消购买方式">
                         <el-checkbox  v-for="(value,index) in sell_type" v-model="value.checked" :key="index" >{{value.name}}</el-checkbox>
                    </el-form-item> -->
                    <el-form-item label="Product Category"> <!-- 商品分类 -->
                        <el-select v-model="form.categoryType">
                            <el-option v-for="item in categoryType" :key="item.id" :label="item.name" :value="item.id" ></el-option>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="Product Code"><!-- 商品编号 -->
                        <el-input v-model="form.goodsNo"></el-input>
                    </el-form-item>
                    <el-form-item label="Unit"><!-- 单位 -->
                        <el-input v-model="form.unit"></el-input>
                    </el-form-item>
                    <el-form-item label="Tax Rate"><!-- 税率 -->
                      <el-input v-model="form.taxRate">
                        <template slot="append">%</template>
                      </el-input>
                    </el-form-item>
                    <el-form-item label="US Price($)" p>
                        <el-input v-model="form.sellPriceStandard"></el-input>
                    </el-form-item>
                    <el-form-item label="Sales Price(₦)" p>
                        <el-input v-model="form.sellPrice"></el-input>
                    </el-form-item>
                    <el-form-item label="Market Price(₦)">
                      <el-input v-model="form.marketPrice"></el-input>
                    </el-form-item>
                    <el-form-item label="Price BV" v-show="pvDisabled"> <!-- 价格BV -->
                        <el-input v-model="form.pricePv"></el-input>
                    </el-form-item>
<!--                    <el-form-item label="Exchange points" v-show="false"> &lt;!&ndash; 兑换积分 &ndash;&gt;-->
<!--                        <el-input v-model="form.point"></el-input>-->
<!--                    </el-form-item>-->
                    <el-form-item label="Inventory"> <!-- 库存 -->
                        <el-input v-model="form.storeNums"></el-input>
                    </el-form-item>
                    <el-form-item label="Product details"><!-- 商品详情 -->
                        <el-input
                                type="textarea"
                                :rows="2"
                                placeholder="Please enter the content"
                                v-model="form.content">
                        </el-input><!-- 请输入内容 -->
                    </el-form-item>
                    <el-form-item label="order"> <!-- 排序 -->
                        <el-input v-model="form.sort"></el-input>
                    </el-form-item>

                    <el-form-item label="upload images"> <!-- 上传图片 -->
                       <div class='up_load'>
                           <!-- <img v-if="form.cover&&img_show" :src="form.cover" alt=""> -->
                            <leo-uploader
                                @on-success='upLoadSuccess'
                                :request-route="'shop/upload'"
                                ref='up_load'
                                :defaultImageUrl='form.cover'
                            ></leo-uploader>
                        </div>
                    </el-form-item>



            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogEditFormVisible = false">Cancel<!-- 取 消 --></el-button>
                <el-button type="primary" @click.native="handleEdit">Edit<!-- 修 改 --></el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    import network from '@/utils/network'
    import tool from '@/utils/tool'
    import baseInfo from '@/utils/baseInfo'
    import FilterUser from '../../components/FilterUser'
    import permission from '@/utils/permission'
    import Pagination from '@/components/Pagination'
    import filterHelper from '@/utils/filterHelper'
    import {FRONTEND_SERVER} from '@/utils/config'
    import store from './../../utils/vuexStore'
     import LeoUploader from '@/components/Uploader';
    export default {
        name: 'index',
        components: {FilterUser,Pagination,LeoUploader},
        mounted () {
            this.getData();
            // this.$refs.up_load.successImageUrl='';
        },

        data () {
            return {
                tableHeaders: null,
                tableData: null,
                loading: true,
                currentPage: 1,
                totalPages: 1,
                totalCount: 1,
                pageSize: 20,
                multipleSelection: [],
                tool: tool,
                permission: permission,
                baseDecLevels: baseInfo.decLevels(),
                baseEmpLevels: baseInfo.empLevels(),
                filterTypes: null,
                dialogVisible: false,
                dialogLoading: false,
                filterModel: {},
                value:[],
                selectedIds:'',
                dialogEditFormVisible: false,
                dialogEditLoading: false,
                form:{
                    // sellType:[],
                    goodsName:'',
                    type:'',
                    giftType:[],
                    goodsNo:'',
                    unit:'',
                    marketPrice:'',
                    sellPrice:'',
                    sellPriceStandard: '',
                    pricePv:'',
                    point:'',
                    storeNums:'',
                    content:'',
                    sort:'',
                    discount:'',
                    cover:'',
                    textarea:'',
                    sellDiscount:'',
                    categoryType: '',
                    sellType: 1,
                    taxRate: 0,
                },
                submitButtonStat: false,
                goodsType:[],
                GiftTypeArr:[],
                sell_type:[],
                categoryType: [],
                img_show:true,
                pvDisabled: true,
                exchangeRate: baseInfo.exchangeRate(),
            }
        },
        methods: {
            handleSelectionChange(val) {
                this.multipleSelection = val
            },
            handleCurrentChange (page) {
                this.getData(page, this.pageSize)
            },
            handleSizeChange (pageSize) {
                this.getData(this.currentPage, pageSize)
            },
            handleFilterUser(filterData){
                filterHelper.handleFilterUser(this, filterData)
            },
            checkSelectable(row) {
                return row.DONT_DEL !== '1'
            },
            handleFilter() {
                this.getData()
            },
            handlestate(){
                this.$router.push({path: `/shop/goods-add`})
            },
            upLoadSuccess(file){
                this.form.cover=file;
                this.img_show=false;
            },
            handleEditShow(row) {
                this.dialogEditLoading = true
                this.auditId = row.ID
                this.dialogEditFormVisible = true
                let vueObj = this
                network.getData('shop/goods-edit', {id: this.auditId}).then(response => {
                    vueObj.dialogEditLoading = false
                    vueObj.goodsType=response.goodsType
                    vueObj.categoryType = response.categoryType

                    let gift=response.goodsInfo.GIFT_TYPE;
                    let gift_type=response.giftType;

                    let giftType=[];
                    if(gift.length>0){
                        for(let i in gift_type){
                            giftType.push({key:i,name:gift_type[i].name,checked:false})
                            gift.map((v,k)=>{
                                if(v==i){
                                    giftType[i-1].checked=true;
                                }
                            })
                        }
                    }
                    vueObj.GiftTypeArr=giftType

                    // let sell=response.goodsInfo.SELL_TYPE;
                    // let sell_type=response.sellType;
                    // let sellType=[];
                    // if(sell.length>0){
                    //     for(let i in sell_type){
                    //         sellType.push({key:i,name:sell_type[i].name,checked:false})
                    //         sell.map((item,index)=>{
                    //             if(item==i){
                    //                 sellType[i-1].checked=true;
                    //             }
                    //         })
                    //     }
                    // }
                    vueObj.sell_type=response.goodsInfo.SELL_TYPE;
                    vueObj.form.goodsName=response.goodsInfo.GOODS_NAME
                    vueObj.form.sellDiscount=response.goodsInfo.SELL_DISCOUNT
                    vueObj.form.goodsNo=response.goodsInfo.GOODS_NO
                    vueObj.form.type=response.goodsInfo.TYPE
                    vueObj.form.unit=response.goodsInfo.UNIT
                    vueObj.form.marketPrice=response.goodsInfo.MARKET_PRICE
                    vueObj.form.sellPrice=response.goodsInfo.SELL_PRICE
                    vueObj.form.sellPriceStandard=response.goodsInfo.SELL_PRICE_STANDARD
                    vueObj.form.pricePv=response.goodsInfo.PRICE_PV
                    vueObj.form.point=response.goodsInfo.POINT
                    vueObj.form.storeNums=response.goodsInfo.STORE_NUMS
                    vueObj.form.content=response.goodsInfo.CONTENT
                    vueObj.form.sort=response.goodsInfo.SORT
                    vueObj.form.id=response.goodsInfo.ID
                    vueObj.form.cover=response.goodsInfo.COVER
                    vueObj.form.categoryType=parseInt(response.goodsInfo.CATEGORY_TYPE)
                    vueObj.form.taxRate=response.goodsInfo.TAX_RATE
                    // vueObj.form.sellType=vueObj.form.sellType.map((item,index)=>{
                    //   return response.goodsInfo.SELL_TYPE.some(val=>(index+1).toString()==val)
                    //   })

                    this.$forceUpdate()

                })
            },
            handleEdit() {
                this.dialogEditFormVisible = false
                this.$message({
                    message: 'Modifying data',//正在修改数据
                    type: 'info'
                })
                let path = 'shop/goods-edit'

                // let sen_sell=[];
                // this.sell_type.map((item,index)=>{
                //     if(item.checked){
                //         sen_sell.push(item.key);
                //     }
                // })
                // this.form.sellType=sen_sell;

                let sen_gift=[];
                this.GiftTypeArr.map((item,index)=>{
                    if(item.checked){
                        sen_gift.push(item.key);
                    }
                })
                this.form.giftType=sen_gift;
                this.form.sellType = 1

                network.postData(path, {...this.form}).then(response => {
                    this.$message({
                        message: response,
                        type: 'success'
                    })
                    this.getData(this.currentPage, this.pageSize)
                }).catch(response => {
                })
            },

            handleDel(id = null) {
                let obj = this
                this.$confirm('Determine to delete the selected data？', 'Hint', {//'确定删除选定的数据？', '提示'
                    confirmButtonText: 'Confirm',//确定
                    cancelButtonText: 'Cancel',//取消
                    type: 'warning'
                }).then(() => {
                    let selectedIds = []
                    if (id === null) {
                        for (let val of obj.multipleSelection) {
                            selectedIds.push(val.ID)
                        }
                    } else {
                        selectedIds.push(id)
                    }
                    return network.postData(`shop/goods-delete`, {
                        selected: selectedIds
                    })
                }).then(response => {
                    this.$message({
                        message: response,
                        type: 'success'
                    })
                    obj.getData(obj.currentPage, obj.pageSize)
                }).catch(response => {

                })
            },
            getData (page, pageSize) {
                let filterData = this.filterModel
                /*this.allData = response*/
                network.getPageData(this, 'shop/index', page, pageSize, this.filterModel, response=>{
                    console.log(response)
                    this.filterTypes = response.filterTypes

                })
            },
            handleGoodUp(id){
                console.log(id);
                network.postData('shop/goods-status',{selectedIds:id,status:1})
                .then(response=>{
                    this.$message({
                        message: response,
                        type: 'success'
                    })
                    this.getData(this.currentPage, this.pageSize)
                })
            },
            handleGoodDown(id){
                network.postData('shop/goods-status',{selectedIds:id,status:0})
                .then(response=>{
                    this.$message({
                        message: response,
                        type: 'success'
                    })
                    this.getData(this.currentPage, this.pageSize)
                })
            },

            handleExport(){
                this.$confirm(`Determine to export the selected data？`, 'Hint', {//确定要导出当前数据吗？`, '提示'
                    confirmButtonText: 'Confirm',//确定
                    cancelButtonText: 'Cancel',//取消
                    type: 'warning'
                }).then(() => {
                    return network.getData(`shop/goods-list-export`, this.filterModel)
                }).then(response => {
                    this.$message({
                        message: response,
                        type: 'success'
                    })
                }).catch(response => {

                })
            },
        },
        watch:{
            // 监听商品分类,控制PV是否展示
            'form.categoryType': {
                deep: true,
                handler(modern, origin) {
                    this.pvDisabled = (parseInt(modern) === 1)
                }
            },
            // 监听商品标准价格,自动计算销售价格
            'form.sellPriceStandard': {
                deep: true,
                handler(modern, origin) {
                    this.form.sellPrice = modern * this.exchangeRate
                }
            },
        },
    }

</script>

<style scoped>
    .table-box .el-form-item__label {
        width: 100px;
        color: #99a9bf;
    }

    .table-box .el-form-item {
        width: 30%;
        margin-right: 0;
        margin-bottom: 0;
    }
</style>
