<template>
  <div class="app-container">
    <el-card class="box-card goods-manage-card">
      <div slot="header" class="clearfix">
        <el-radio-group v-model="radiomodel" class="radiomodels" @change="radiomodelbtn">
          <el-radio-button :label="1">上架销售中（{{onsale_count}}）</el-radio-button>
          <el-radio-button :label="2">仓库中的商品（{{downsale_count}}）</el-radio-button>
          <el-radio-button :label="3">审核记录</el-radio-button>
          <el-radio-button :label="4">最近删除（{{del_count}}）</el-radio-button>
        </el-radio-group>
      </div>
      <el-form :inline="true" class="queryFormInline" :model="formInline">
        <el-row :span="24" type="flex" align="middle" justify="space-between">
          <el-col :span="20">
            <el-form-item label="商品编号">
              <el-input v-model="formInline.goods_id" size="mini" placeholder="填写商品编号"></el-input>
            </el-form-item>
            <el-form-item label="商品名称">
              <el-input v-model="formInline.goods_name" size="mini" placeholder="填写商品名称"></el-input>
            </el-form-item>
            <el-form-item label="商品状态" v-show="radiomodel==3">
              <el-select v-model="formInline.status" placeholder="请选择" size="mini" style='width:100px;'>
                <el-option label="全部" value="5" v-if='radiomodel==3'></el-option>
                <el-option label="审核中" value="1" v-if='radiomodel==3'></el-option>
                <el-option label="审核拒绝" value="2" v-if='radiomodel==3'></el-option>
              </el-select>
            </el-form-item>
            <el-form-item label="发布时间">
              <el-date-picker
                style='width:315px;'
                v-model="formInline.uptime"
                type="daterange"
                range-separator="至"
                size="mini"
                format="yyyy 年 MM 月 dd 日"
                value-format="timestamp"
                start-placeholder="开始日期"
                end-placeholder="结束日期">
              </el-date-picker>
            </el-form-item>

            <el-form-item label="价格区间">
              <el-input v-model="formInline.price_min" size="mini" placeholder="最小价格" style="width:100px;"></el-input>
              -
              <el-input v-model="formInline.price_max" size="mini" placeholder="最大价格" style="width:100px;"></el-input>
            </el-form-item>
            <el-form-item>
              <el-button
                type="primary"
                size="mini"
                @click="handleQuery"
              >查询
              </el-button>
            </el-form-item>
          </el-col>
          <el-col :span="4">
            <div style="float: right">
              <el-button
                style="float:right;margin-left: 10px;"
                type="danger"
                v-if='radiomodel===2'
                size="mini"
                :disabled="multiple"
                @click="handledelsale('9','del','all')"
              >批量删除
              </el-button>
              <el-button
                style="float:right;margin-left: 10px;"
                type="danger"
                v-if='radiomodel==4'
                size="mini"
                :disabled="multiple"
                @click="handledelgrain('9','all')"
              >彻底删除
              </el-button>
              <el-button
                v-if='radiomodel==1'
                style="float:right;margin-left: 20px;"
                type="primary"
                :disabled="multiple"
                size="mini"
                @click="handleUpsale('9','down','all')"
              >批量下架
              </el-button>
              <el-button
                v-if='radiomodel==2'
                style="float:right;margin-left: 20px;"
                type="primary"
                :disabled="multiple"
                size="mini"
                @click="handleUpsale('9','up','all')"
              >批量申请上架
              </el-button>
              <el-button
                v-if='radiomodel==4'
                :disabled="multiple"
                style="float:right;margin-left: 20px;"
                type="primary"
                size="mini"
                @click="handledelsale('9','return','all')"
              >批量还原
              </el-button>
              <el-button
                v-if='radiomodel==3'
                :disabled="multiple"
                style="float:right;margin-left: 20px;align-items:normal"
                type="primary"
                size="mini"
                @click="handleCancelUpale"
              >批量取消申请上架
              </el-button>
            </div>
          </el-col>
        </el-row>
      </el-form>
      <el-table v-loading="loading" :data="freightList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center"/>
        <el-table-column label="商品主图" width="95" align="center">
          <template slot-scope="scope">
            <img :src="scope.row.default_image" alt="" style="width:60px;height:60px;">
          </template>
        </el-table-column>
        <el-table-column label="商品编号" align="center" prop="goods_id"/>
        <el-table-column label="商品名称" align="center" prop="goods_name"/>
        <el-table-column label="协议价" align="center" prop="">
          <template slot-scope="scope">
            {{scope.row.js_price/100}}元
          </template>
        </el-table-column>
        <!-- <el-table-column label="类型" align="center" :formatter="formatType" prop="ChargeType"/> -->
        <el-table-column label="库存量" align="center" prop="stock"/>
        <el-table-column label="商品状态" align="center" prop>
          <template slot-scope="scope">
            <span v-if="radiomodel==1||radiomodel==2">
              {{scope.row.is_onsale===0?'下架':'上架'}}
            </span>
            <span v-if="radiomodel==3">
              {{scope.row.up_onsale===1?'审核中':'审核拒绝'}}
            </span>
            <span v-if="radiomodel==4">
              {{scope.row.is_on===0?'已删除':'彻底删除'}}
            </span>
          </template>
        </el-table-column>
        <el-table-column label="发布时间" align="center" :formatter="formatTime" prop="add_time"/>
        <el-table-column label="审核说明" align="center" prop="last_perate_content" width="240px"/>
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <div v-if='radiomodel==3&&scope.row.up_onsale===1'>
              <el-button
                size="mini"
                type="text"
                @click="handleCancelUpsale(scope.row)"
              >取消上架申请
              </el-button>
            </div>
            <div v-else>
              <el-button
                v-if="radiomodel==1"
                size="mini"
                type="text"
                @click="handleUpsale(scope.row,'down','one')"
              >下架
              </el-button>
              <el-button
                v-if="radiomodel==2"
                size="mini"
                type="text"
                @click="handleUpsale(scope.row,'up','one')"
              >申请上架
              </el-button>
              <el-button
                v-if="radiomodel==4"
                size="mini"
                type="text"
                @click="handledelsale(scope.row,'return','one')"
              >还原
              </el-button>
              <el-divider direction="vertical" v-if="radiomodel!=3"></el-divider>
              <el-button
                v-if="radiomodel!=4 && radiomodel!=1"
                size="mini"
                type="text"
                @click="editgoods(scope.row)"
              >编辑
              </el-button>
              <el-divider direction="vertical" v-if="radiomodel!=4 && radiomodel!=1"></el-divider>
              <el-button
                size="mini"
                type="text"
                @click="lookdetail(scope.row)"
              >预览
              </el-button>
              <el-divider direction="vertical" v-if="radiomodel!=1"></el-divider>
              <el-button
                v-if="radiomodel!=4&&radiomodel!=1"
                size="mini"
                type="text"
                @click="handledelsale(scope.row,'del','one')"
              >删除
              </el-button>
              <el-button
                v-if="radiomodel==4"
                size="mini"
                type="text"
                @click="handledelgrain(scope.row,'one')"
              >彻底删除
              </el-button>
            </div>
          </template>

        </el-table-column>
      </el-table>
      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="formInline.page"
        :limit.sync="formInline.limit"
        @pagination="getList"
      />
      <!-- 商品编辑-->
<!--      <el-dialog title="编辑商品" :visible.sync="editisOpen" v-if="editisOpen" width="70%" class="freightTemplate-add">-->
<!--        <editGood :option="goodsid" @closeEditDialog="closeEditGoods"></editGood>-->
<!--      </el-dialog>-->
      <el-dialog title="商品详情" :visible.sync="isOpen" center v-if="isOpen" width="70%" class="freightTemplate-add"
                 :close-on-click-modal="false">
        <goodDetail :goods-id="goodDetails"></goodDetail>
      </el-dialog>
    </el-card>
  </div>
</template>
<script>
  import goodDetail from './components/goodsdetail'
  import editGood from '@/views/system/goods/add/index'
  import { getlistGoods, shelvesStatus, delgoodsStatus,cancelOnsale,cancelOnsaleAllData } from '@/api/module/goodsgement'
  import {dateFormat} from '@/utils'

  export default {
    name: "freight",
    data() {
      return {
        goodDetails: {
          goods_id: ''
        },
        // editisOpen: false,//编辑
        downsale_count: '',//仓库数量
        onsale_count: '',//上架数量
        del_count: '',//删除数量
        radiomodel: 1,
        formInline: {
          page: 1,
          limit: 20,
          goods_name: '',
          goods_id: '',
          status: '5',
          uptime: '',
          price_min: '',
          price_max: ''
        },
        // fullHeight: 0,
        // tableHeight: 0,
        // 遮罩层
        loading: false,
        // 选中数组
        selectionsList:[],
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // freight表格数据
        freightList: [],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        isOpen: false,
        // 查询参数
        queryParams: {
          page: 1,
          limit: 20,
          seller_id: null,
          name: null,
          sort: null,
          is_default: null,
          charge_type: null,
          dispatching: null,
          disdispatching: null,
          publish: null,
          created: null,
          modified: null,
        },
        // 表单参数
        goodsid: 0,
        // 表单校验
        rules: {
          name: [
            {required: true, message: "模板名称不能为空", trigger: "blur"}
          ],
        }
      };
    },
    components: {
      goodDetail,
      editGood
    },
    created() {
      if( this.$route.query.goodsStatus ) {
        this.radiomodel = Number(this.$route.query.goodsStatus);
      }
      this.getList();
      // this.$nextTick(() => {
      //   let headerHeight = document.getElementsByClassName('queryFormInline')[0].clientHeight
      //   this.fullHeight = document.getElementsByClassName('box-card')[0].clientHeight - headerHeight
      // })
    },
    watch: {
      // fullHeight(val) {
      //   let headerHeight = document.getElementsByClassName('queryFormInline')[0].clientHeight
      //   let formHeight = document.getElementsByClassName('clearfix')[0].clientHeight
      //   this.tableHeight = val - formHeight - 40 - headerHeight
      // }
    },
    methods: {
      handledelgrain(row, isall) { //彻底删除
        let good_id, is_on, title, message
        if (isall == 'one') {
          good_id = [row.goods_id]
          is_on = 2
          title = "彻底删除"
          message = "此操作将彻底删除该商品，是否继续？"

        } else if (isall == 'all') {
          good_id = this.ids

          is_on = 2
          title = "彻底删除"
          message = "此操作将彻底删除选中的商品，是否继续？"


        }
        let data = {
          'goods_id': good_id,
          'is_on': is_on
        }
        this.$msgbox({
          title: title,
          message: message,
          center: true,
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              delgoodsStatus(data).then(res => {
                if (res.code == 1) {
                  done()
                  this.getList()
                }
              })
            } else {
              done();
            }
          }
        }).then(action => {
          this.$message({
            type: 'success',
            message: '操作成功！'
          });
        });
      },
      handledelsale(row, status, isall) {//删除还原
        let good_id, is_on, title, message
        if (isall == 'one') {
          good_id = [row.goods_id]
          if (status == 'del') { // 0 删除 1还原
            is_on = 0
            title = "删除"
            message = "是否删除该商品！"
          }
          if (status == 'return') {
            is_on = 1
            title = "还原"
            message = "是否还原该商品！"
          }
        } else if (isall == 'all') {
          good_id = this.ids
          if (status == 'del') {
            is_on = 0
            title = "批量删除"
            message = "是否删除选中的商品！"
          }
          if (status == 'return') {
            is_on = 1
            title = "批量还原"
            message = "是否还原选中的商品！"
          }
        }
        let data = {
          'goods_id': good_id,
          'is_on': is_on
        }
        this.$msgbox({
          title: title,
          message: message,
          center: true,
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              delgoodsStatus(data).then(res => {
                if (res.code == 1) {
                  done()

                  this.$message({
                    type: 'success',
                    message: '操作成功！'
                  });
                  this.getList()
                } else {
                  done()
                  this.$message({
                    type: 'warning',
                    message: res.message
                  });
                }

              })
            } else {
              done();
            }
          }
        }).then(action => {
          //  this.$message({
          //    type: 'success',
          //    message: '操作成功！'
          //  });
        });
      },

      // 下架/申请上架
      handleUpsale(row, status, isall) { //上下架
        //console.log(442,row);
        let good_id, is_onsale, title, message
        if (isall == 'one') {
          good_id = [row.goods_id]
          if (status == 'up') { // 0 下架 1上架
            is_onsale = 1
            title = "商品上架"
            message = "是否上架该商品"
          }
          if (status == 'down') {
            is_onsale = 0
            title = "商品下架"
            message = "是否下架该商品！"
          }
        } else if (isall == 'all') {
          good_id = this.ids
          if (status == 'up') {
            is_onsale = 1
            title = "商品批量上架"
            message = "是否上架选中的商品！"
          }
          if (status == 'down') {
            is_onsale = 0
            title = "商品批量下架"
            message = "是否下架选中的商品！"
          }
        }
        let data = {
          'goods_id': good_id,
          'is_onsale': is_onsale
        }
        this.$msgbox({
          title: title,
          message: message,
          center: true,
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              shelvesStatus(data).then(res => {
                if (res.code == 1) {
                  done()
                  this.getList()
                }else {
                  this.$message({type: 'success', message: res.message ? res.message : '操作失败'});
                }
              })
            } else {
              done();
            }
          }
        }).then(action => {
          this.$message({
            type: 'success',
            message: '操作成功！'
          });
        });

      },
      /** 批量取消申请上架 */
      handleCancelUpale() {
        // id组成的数组 this.ids
        if( this.ids.length <= 0 ) {
          this.$message({type:'warning',message:'请先选择需要操作的数据'});
          return
        }

        let isContinue = true;
        for (let i = 0; i < this.selectionsList.length; i++) {
          if(this.selectionsList[i].up_onsale != 1) {
            isContinue = false
            break
          }
        }
        //
        if (!isContinue) {
          this.$message({type:'warning',message:'所选商品中有部分未申请上架，请重新勾选'});
          return
        }

        let ids = {goods_id:this.ids.join(',')};

        this.$confirm('是否批量取消所选中的商品的上架申请', '批量取消申请上架', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
          center: true
        }).then(async() => {
          let res = await cancelOnsaleAllData(ids)
          if (res.code == 1) {
            this.$message({type:'success',message:'批量取消成功'});
          } else {
            this.$message({type:'success',message: res.message ? res.message : '批量取消失败'});
          }
          this.getList()
        }).catch(() => {});
      },
      // 取消上架申请
      handleCancelUpsale(row) {
        let id = {
          goods_id: 0
        };
        id.goods_id = row.goods_id ? row.goods_id : 0;
        this.$msgbox({
          title: '取消商品上架申请',
          message: "是否取消选中商品的上架申请！",
          center: true,
          showCancelButton: true,
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          beforeClose: (action, instance, done) => {
            if (action === 'confirm') {
              cancelOnsale(id).then(res => {
                if (res.code == 1) {
                  done()
                  this.getList()
                }else {
                  this.$message({type: 'error', message: res.message ? res.message : '操作失败'});
                }
              })
            } else {
              done();
            }
          }
        }).then(action => {
          this.$message({
            type: 'success',
            message: '操作成功！'
          });
        });
      },
      editgoods(row) {//商品编辑
        // this.editisOpen = true
        let goodsId = Number(row.goods_id);
        // let goodsParam = {
        //   goods_id: Number(row.goods_id)
        // };
        this.$router.push({
          path: '/system/goods/editgoods',
          query: { goods_id : goodsId }
        });
        //this.$router.push({ path: '/system/goods/editgoods' });
      },
      lookdetail(row) {//预览商品详情
        this.isOpen = true
        this.goodDetails.goods_id = row.goods_id
      },
      radiomodelbtn(val) { //头部切换
        //console.log(505,val)
        this.formInline = {
          page: 1,
          limit: 20,
          goods_name: '',
          goods_id: '',
          status: '5',
          uptime: '',
          price_min: '',
          price_max: ''
        }
        this.getList()
      },
      closeEditGoods(val) {
        this.editisOpen = false;
        this.getList();
      },
      //格式化状态
      formatDefault(row) {
        var types = row.IsDefault
        var optDes = ''
        if (types == 1) {
          optDes = "是"
        } else if (types == 0) {
          optDes = "否"
        }
        return optDes
      },
      //格式化时间
      formatTime(row) {
        var Time = row.add_time
        var newtime = ""
        if (Time > 0) {
          newtime = dateFormat(Time * 1000, "Y-m-d H:i:s");
        }
        return newtime
      },
      /** 查询freight列表 */
      getList() {
        //debugger
        let data = {
          page: this.formInline.page,
          limit: this.formInline.limit,
        }

        if (this.radiomodel === 1) {
          data['is_onsale'] = 1
          data['is_on'] = 1
          data['up_onsale'] = 0
        }
        if (this.radiomodel === 2) {
          data['is_onsale'] = 0
          data['is_on'] = 1
          data['up_onsale'] = 0
        }
        if (this.radiomodel === 3) {
          data['up_onsale'] = Number(this.formInline.status)
          data['is_onsale'] = 0
          data['is_on'] = 1
        }
        if (this.radiomodel === 4) {
          data['is_on'] = 0
        }
        if (this.formInline.goods_name) {
          data['goods_name'] = this.formInline.goods_name
        }
        if (this.formInline.goods_id) {
          data['goods_id'] = this.formInline.goods_id
        }
        if (this.formInline.uptime && this.formInline.uptime.length == 2) {
          data['start_time'] = this.formInline.uptime[0] / 1000
          data['end_time'] = this.formInline.uptime[1] / 1000 + 86399
        }
        if (this.formInline.price_min && this.formInline.price_max) {
          data['price_min'] = this.formInline.price_min
          data['price_max'] = this.formInline.price_max
        }

        //console.log("查询list的参数：", data);

        getlistGoods(data).then(res => {
          if (res.data) {
            this.freightList = res.data.list;
            this.total = res.data.count;
            this.downsale_count = res.data.downsale_count//仓库数量
            this.onsale_count = res.data.onsale_count//上架数量
            this.del_count = res.data.del_count//删除数量
          }
        });
      },
      // 取消按钮
      cancel() {
        this.isOpen = false;
        this.reset();
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.formInline.page = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.selectionsList = selection;
        this.ids = selection.map(item => item.goods_id)
        this.single = selection.length !== 1
        this.multiple = !selection.length
      },


    } //methods结束
  };
</script>
<style scoped lang="scss" type="text/stylus">
  .app-container {
    width: 100%;
    height: 100%;
  }
  .goods-manage-card >>> .el-card__body {
    height: calc(100% - 61px);
    overflow-y : auto;
  }

  .freightTemplate-add {
    /deep/ .el-dialog {
      height: 80%;
      overflow: hidden;
    }

    /deep/ .el-dialog__body {
      height: calc(100% - 60px);
      overflow-x: hidden;
      overflow-y: scroll;
    }
  }

  .radiomodels .el-radio-button {
    margin: 0 10px;
  }

  /deep/ .radiomodels .el-radio-button .el-radio-button__inner {
    border: 1px solid #DCDFE6 !important;
    border-radius: 4px !important;
  }

  /deep/ .radiomodels .el-radio-button .el-radio-button__orig-radio:checked + .el-radio-button__inner {
    box-shadow: none;
  }

  .queryFormInline {
    padding-bottom: 20px;
  }
</style>
