<template>
  <div class="yqshop-wrapper">
    <bread-crumb :curmbFirst="curmbFirst" :curmbSecond="curmbSecond"></bread-crumb>
    <div class="yqshop-content screenSet" id="screenSet">
      <div class="header-title">商品管理</div>
      <el-form ref="searchForm" :model="searchForm" label-width="80px" label-suffix=":" :inline="true">
        <el-row :gutter="30" type="flex" style="margin-top: 10px">
          <el-col :span="18">
            <el-form-item label="商品名称">
              <el-input v-model="searchForm.goodsName" size="small" placeholder="请输入商品名称"></el-input>
            </el-form-item>
            <el-form-item label="商品ID">
              <el-input v-model="id" size="small" placeholder="请输入商品ID"></el-input>
            </el-form-item>
            <el-form-item label="商品类型">
              <el-select
                  v-model="searchForm.goodsType"
                  placeholder="请选择商品类型"
                  size="small"
                  clearable>
                <el-option
                    v-for="(item,index) in goodsTypes"
                    :key="index"
                    :label="item.categoryName"
                    :value="item.id"
                ></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="6" style="text-align: right">
            <el-button type="primary" size="small" @click="searchList">查询</el-button>
            <el-button type="default" size="small" @click="resetForm" style="margin-left:0;">重置</el-button>
          </el-col>
        </el-row>
        <el-row :gutter="30" type="flex" style="margin-top: 10px">
          <el-col :span="12">
            <el-button type="primary" size="small" @click="batchOpt('on')">批量上架</el-button>
            <el-button type="primary" size="small" @click="batchOpt('off')">批量下架</el-button>
          </el-col>

          <el-col :span="12" style="text-align: right">
            <el-button type="primary" size="small" @click="exportOpt">批量导出商品</el-button>
            <el-button v-if="isSSO" type="primary" size="small" @click="batchOpt(3)">批量导入商品</el-button>
            <el-button type="primary" size="small" @click="edit('add')">新建单个商品</el-button>
          </el-col>
        </el-row>

      </el-form>
      <el-table ref="multipleTable" :data="tableData" class="item-table" style="width: 100%;margin-top: 10px;" @selection-change="handleSelectionChange">
        <el-table-column
          type="selection"
          fixed
          width="55">
        </el-table-column>
        <el-table-column prop="goodsId" label="商品ID" width="120" align="center">
        </el-table-column>
        <el-table-column prop="goodsName" label="商品名称" width="140" align="center" show-overflow-tooltip></el-table-column>
        <el-table-column prop="type" label="商品类型" width="100" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.goodsTypeStr }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="商品状态" width="100" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.goodsStatus | rangeStatus }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="quantityOfSale" label="销量" width="120" align="center">

        </el-table-column>
        <el-table-column prop="size" label="规格" width="100" align="center">

        </el-table-column>
        <el-table-column prop="costPrice" label="价格" width="120" align="center">
          <template slot-scope="scope">
            <span>{{scope.row.costPrice | rangePrice}}</span>
          </template>
        </el-table-column>
        <el-table-column prop="saleTime" label="发布时间" width="150" align="center">

        </el-table-column>

        <el-table-column label="操作" width="200" align="center" fixed="right">
          <template slot-scope="scope">
            <div v-if="scope.row.goodsStatus == 0">
              <el-button @click="edit(scope.row)" type="text" size="small">编辑</el-button>
              <el-button @click="shelfOpt(scope.row,2)" type="text" size="small">上架销售</el-button>
              <!-- <el-button @click="shelfOpt(scope.row,3)" type="text" size="small">删除</el-button> -->
            </div>
            <div v-if="scope.row.goodsStatus == 1">
              <el-button @click="edit(scope.row)" type="text" size="small">编辑</el-button>
              <el-button @click="shelfOpt(scope.row,1)" type="text" size="small">下架</el-button>

            </div>
            <div v-if="scope.row.goodsStatus == 2">
              <el-button @click="edit(scope.row)" type="text" size="small">编辑</el-button>

              <el-button @click="shelfOpt(scope.row,2)" type="text" size="small">上架销售</el-button>
              <!-- <el-button @click="shelfOpt(scope.row,3)" type="text" size="small">删除</el-button> -->
            </div>
            <div v-if="scope.row.goodsStatus == 3">
              <!-- <el-button @click="edit(scope.row)" type="text" size="small">编辑</el-button>
              <el-button @click="shelfOpt(scope.row,1)" type="text" size="small">下架</el-button>
              <el-button @click="shelfOpt(scope.row,2)" type="text" size="small">上架销售</el-button>
              <el-button @click="shelfOpt(scope.row,3)" type="text" size="small">删除</el-button> -->
            </div>
          </template>
        </el-table-column>
      </el-table>
      <div class="pagination">
        <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleNumChange"
            :current-page="searchForm.pageNo"
            :page-sizes="[10, 30, 50, 100]"
            :page-size="searchForm.pageSize"
            layout="total, sizes, prev, pager, next, jumper"
            :total="totalRows"
        ></el-pagination>
      </div>
    </div>
    <el-dialog
      title="批量导入"
      :visible.sync="batchDialog"
      width="30%"
      center>
      <el-dialog
        width="30%"
        title="导入失败原因"
        :visible.sync="innerVisible"
        append-to-body>
        <div class="upload-error">
          <div class="error-tem" style="padding:5px" v-for="(item,index) in validateFailedList" :key="index">
            {{'第'+item.rowNumber+'行：'}}{{item.validateResultList.join(',')}}
          </div>
        </div>
      </el-dialog>
      <div class="batch-dia">
        <div class="batch-dia-item">
          <span class="s-l">1、下载模板</span>
          <span class="s-r" @click="uploadTemp"><i class="el-icon-upload"></i>下载</span>
        </div>
        <div class="batch-dia-item">
          <span class="s-l">2、根据模板填写信息</span>

        </div>
        <div class="batch-dia-item">
          <span class="s-l">3、上传文件</span>
          <span class="s-r">
            <el-upload
              class="upload-demo"
              action="#"
              :on-preview="handlePreview"
              :on-remove="handleRemove"
              :before-remove="beforeRemove"
              :before-upload="getBatchUpload"
              multiple
              :limit="1"

              :file-list="fileList">
                 <i class="el-icon-upload"></i>上传
            </el-upload>
           </span>
        </div>
      </div>
      <span slot="footer" class="dialog-footer" style="text-align: right;">
        <!-- <el-button @click="centerDialogVisible = false">取 消</el-button> -->
        <el-button type="primary" @click="batchDialog = false">完成</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script>
  import { openLoading, closeLoading } from "../../utils/utils";
  import BreadCrumb from "@/components/breadcrumb.vue";
  import { getRangeList,updateRangeStatus, getGoodsExportUrl, getOrdersExportUrl } from "../../utils/yqrange/yqrangeApi";
  import { getGoodsList,batchOnOff,uploadExcel} from '@/utils/goods';
  import { getBaseUrl } from '@/utils/index'
  var typeList = [{
    categoryName: "短信额度",
    id: 1,
  }, {
    categoryName: "学习卡",
    id: 2,
  },  {
    categoryName: "职称考卡",
    id: 3,
  },{
    categoryName: "医疗器械",
    id: 4,
  },{
    categoryName: "药品",
    id: 5,
  },{
    categoryName: "检测服务",
    id: 337,
  }];
  export default {
    components: {
      BreadCrumb
    },
    data(){
      return{
        curmbFirst: '云鹊店铺',
        curmbSecond: '商品管理',
        showAllFlag: false,
        showNewFlag: false,
        batchDialog:false,
        id:'',
        searchForm: {
          goodsIdList:[],
          goodsName	:'',
          goodsType	:'',
          pageNo:1,
          pageSize:	10,
          storeId:0,
        },
        innerVisible:false,
        selectList:[],
        batchParm:{
          batchUpdateSaleStatusReq: {
            goodsIdList: [],
            userId: 0
          },
          onOff: ""
        },
        fileList:[],
        totalRows: 0,
        tableData: [],
        goodsTypes:[],
        typeList: [],
        //uploadUrl:getBaseUrl('store/goods/import'),
        postData:{},
        validateFailedList:[],
        isSSO: 0, // 是否是sso后台管理员 1是 0否
      }
    },
    created() {
      this.getLists()
      this.getLever()
      const {storeId} = this.$route.query;
      this.searchForm.storeId = Number(storeId) || 0;
      // if(storeId){
      //   this.searchForm.storeId = storeId
      // }
    },
    filters:{
      rangeType(type){
        let name = ''
        for(let i=0;i<typeList.length;i++){
          if(type == typeList[i].id){
            name = typeList[i].categoryName;
            break;
          }
        }
        return name
      },
      rangeStatus(status){
        let str = ''//0待上架，1已上架，2已下架，3定时上架
        if(status == 1){
          str = '已上架'
        }else if(status == 0){
          str = '待上架'
        }else if(status == 2){
          str = '已下架'
        }else if(status == 3){
          str = '定时上架'
        }
        return str
      },
      rangePrice(price){
        let str = '￥'
        str += price/100
        return str
      }
    },
    methods: {
      handlePreview(){},
      handleRemove(){},
      beforeRemove(){},
      handleSelectionChange(val){
        console.log(val)
        this.selectList = val
      },

      //批量上传
      getBatchUpload(file) {
        let self = this;
        let arr = file.type.split('/');
        let ext = "." + arr[1];
        let name = file.name;
        let type = name.substring(name.lastIndexOf('.') + 1);
        if (type !== 'xls' && type !== 'xlsx') {
          self.$message({
            message: '上传文件只能是 xls、xlsx格式!',
            type: 'warning'
          });
         return;
        }
        let reader = new FileReader();
        reader.onload = function (e) {
            let fileJson = {
                fileName: file.name,
                file: e.target.result.substr(e.target.result.indexOf("base64,") + 7),
                ext: ext
            };

            let fileArray = [{
                type: 'patient',
                base64: fileJson
            }];

            let req = {
                base64Str : e.target.result.substr(e.target.result.indexOf("base64,") + 7),
                storeId:self.searchForm.storeId
                //import_type: 2,
            };
            //req.token = localStorage.getItem('storageToken');
            //self.postData = JSON.stringify(req);

            uploadExcel(req).then(res => {

              if(res.code != '000000'){
                return self.$message({
                  message: res.message || '上传失败，请重新上传!',
                  type: 'error'
                });
              }
              if(res.data.allPass){

                self.$message({
                  message: '上传成功!',
                  type: 'success'
                });
                self.batchDialog = false
                setTimeout(()=>{
                  self.getLists()
                },2000)
              }else{
                self.innerVisible = true
                self.validateFailedList = res.data.validateFailedList || []
              }


            }).catch(err => {
              console.log(`上传报错`, err);
            })
        };
        reader.readAsDataURL(file);
      },
      uploadTemp(){
        // let url = "https://file.yunqueyi.com/trade/store/goods_import_template.xlsx"
        const url = 'https://file.yunqueyi.com/trade/store/20210129/goods_import_template.xlsx';
        window.location.href = url
      },
      getLever(id=0){

        this.GET("store/category/"+id).then(res => {
            console.log(res)
            this.goodsTypes = res.data
        });
      },
      getLists(){
        openLoading(this);
        getGoodsList(this.searchForm).then((res)=>{
          if(res.code != '000000'){
            return this.$message({
              message: res.message,
              type: 'error'
            });
          }
          closeLoading(this);
          if(res.data == null){
            return this.$message({
              message: '分页数据加载失败',
              type: 'error'
            });
          }
          this.tableData = res.data.goodsList
          this.totalRows = res.data.totalCount
          this.isSSO = res.data.isSSO;
        })
      },
      //获取商品id
      getIdsByArr(d){
        let a = []
        for(let i=0;i<d.length;i++){
          a.push(d[i].goodsId)
        }
        return a;
      },

      //批量 上下架操作
      batchOpt(type){
        if(type == 3){//批量导入
          this.batchDialog = true
        }else{
          if(this.selectList.length == 0){
            return this.$message({
              message: '请选择商品',
              type: 'warning'
            });
          }
          this.batchParm.onOff = type
          this.batchParm.batchUpdateSaleStatusReq.goodsIdList = this.getIdsByArr(this.selectList)
          batchOnOff(this.batchParm).then((res)=>{
            if(res.code == '000000'){
              this.selectList = []
              this.$refs.multipleTable.clearSelection();
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              setTimeout(()=>{
                this.getLists()
              },2000)

            }
          })
        }
      },
      edit(row){
        const { goodsType } = row;
        let url = ''
        if(row == 'add'){
          url = `/create-good?id=add&storeId=${this.searchForm.storeId}&inputType=1`
        }else{
          url = `/create-good?id=${row.goodsId}&storeId=${this.searchForm.storeId}&goodsType=${goodsType}`
        }
        // this.$store.dispatch('goodsManage/changeGoodsInfo', {...row});
        this.$router.push({
          path: url
        })
      },

      //上架  下架
      shelfOpt(row,type){
        let str = '',
            btn1 = '',
            btn2 = ''
        if(type == 1){
          str = `确定下架商品吗？<br/>下架后将不再出售`
          btn1 = '下架'

        }else if(type == 2){
          str = `确定上架商品吗？<br/>上架后将开始出售`
          btn1 = '上架'

        }else if(type == 3){
          str = `确定删除商品吗？<br/>删除后商品信息将都不保留`
          btn1 = '删除'
        }
        this.$confirm(str, '', {
          confirmButtonText: btn1,
          cancelButtonText: '取消',
          type: 'warning',
          customClass: 'range-make-box',
          dangerouslyUseHTMLString:true
        }).then(() => {
          //  confirm
         // this.updateStatus(row.id, "30");
         if(type != 3){
           this.batchParm.onOff = type == 1 ? 'off' : 'on'
           this.batchParm.batchUpdateSaleStatusReq.goodsIdList = [row.goodsId]
           batchOnOff(this.batchParm).then((res)=>{
             if(res.code == '000000'){

               this.getLists()
             }
           })
         }

        }).catch(() => {
          //  cancel
          // this.$message.error("上线失败");
        });
      },

      initPrivilege(){
        let idType = localStorage.getItem('storageIdType');
        this.searchForm.userType = idType;
        // 内部用户:运营人员
        if(idType == "1"){
          this.showAllFlag = true;
          this.showNewFlag = true;
        }
        // 外部用户
        else if(idType == "2"){
          this.showAllFlag = false;
          this.getUserAuth();
        }
      },
      // 外部用户权限
      getUserAuth(){
        let highMainManager = localStorage.getItem('highMainManager');
        let mainManager = localStorage.getItem('mainManager');
        let manager = localStorage.getItem('manager');

        if(highMainManager == "1" || mainManager == "1"){
          this.showNewFlag = true;
        }
        else if(manager == "1"){
          this.showNewFlag = false;
        }
      },

      searchList() {
        openLoading(this);
        if(this.id != ''){
          this.searchForm.goodsIdList = [this.id]
        }else{
          this.searchForm.goodsIdList = []
        }
        this.searchForm.pageNo = 1
        this.getLists()
      },

      resetForm() {
        // this.searchForm = {
        //  goodsIdList:[],
        //  goodsName:'',
        //  goodsType:'',
        //  pageNo:1,
        //  pageSize:	10,

        // };
        this.searchForm.goodsIdList = []
        this.searchForm.goodsName = ''
        this.searchForm.goodsType = ''
        this.searchForm.pageNo = 1
        this.searchForm.pageSize = 10

        this.getLists();
      },

      handleSizeChange(val) {
        this.searchForm.pageSize = val;
        this.searchForm.pageNo = 1;
        this.searchList();
      },
      handleNumChange(val) {
        this.searchForm.pageNo = val;
        this.getLists();
      },
      exportOpt() {
        const { goodsIdList, goodsType, goodsName, storeId } = this.searchForm;

        getGoodsExportUrl({ goodsIdList, goodsType, goodsName, storeId }).then(res => {
          if (res.code != '000000') {
            this.$message({ message: res.message, type: 'error' });
            return;
          }
          window.open(res.data);
        });
      }
    },
  }
</script>
<style lang="scss">
  .yqshop-wrapper{
    .yqshop-content{
      background: #fff;
      padding: 10px;
      .header-title{
        padding: 10px 12px;
        font-size: 13px;
        color: #449284;
        border-bottom: 1px solid #efefef;
      }
    }
    .el-button--text{
      color: #449284;
      font-size: 14px;
      &::after{
        content: '';
        position: relative;
        height: 14px;
        /*border-right: 1px solid #EBEEF5;*/
        border-right: 1px solid #aaaaaa;
        padding-right: 10px;
      }
      &:last-of-type{
        &::after{
          content: '';
          position: relative;
          width: 1px;
          height: 14px;
          border-right: none;
        }
      }
    }
  }
  .batch-dia{
    .batch-dia-item{overflow: hidden;
      .s-l,.s-r{
        float: left;
        padding:10px 0;
        color:#666
      }
      .s-l{
        margin-right: 100px;

      }
      .s-r{
        color:#1989fa;
        cursor: pointer;
      }
      .el-icon-upload{

      }
    }
  }
</style>
