<template>
  <div class="app-container">
    <!-- 查询和其他操作 -->
    <div class="filter-container">
      <el-input
        v-model="listQuery.liveProductId"
        clearable
        class="filter-item"
        style="width: 180px;"
        placeholder="请输入视频号商品id"
      />

      <!-- <el-select v-model="listQuery.channelId" style="width: 260px" class="filter-item" placeholder="请选择渠道" clearable
        filterable>
        <el-option v-for="item in channels" :key="item.id" :label="item.name" :value="item.id" />
      </el-select>-->
      <el-cascader
        v-model="listQuery.jzGoodsId"
        :options="goodsList"
        expand-trigger="hover"
        style="width:400px"
        clearable
        class="filter-item"
        placeholder="请选择商品"
        @change="goodsIdChange"
      />

      <el-button
        v-permission="['GET /admin/localLive/getGoodsList']"
        class="filter-item"
        type="primary"
        icon="el-icon-search"
        @click="handleFilter"
      >查找</el-button>

      <el-button
        v-permission="['POST /admin/localLive/addLocalLiveGoods']"
        class="filter-item"
        type="primary"
        icon="el-icon-edit"
        @click="handleCreate"
      >添加</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="正在查询中。。。"
      border
      fit
      highlight-current-row
      @expand-change="handleExpandChange"
    >
      <el-table-column align="center" type="expand" prop="id" fixed="left">
        <template slot-scope="scope">
          <el-table
            :data="scope.row.externalList"
            style="width:1000px"
            border
            fit
            highlight-current-row
          >
            <el-table-column
              align="center"
              label="规格名称"
              width="200"
              prop="jzGoodsProduct.specifications[0]"
            />
            <el-table-column align="center" label="对外商品Id" prop="jzOutProductId" />
            <el-table-column align="center" label="对外skuId" prop="jzOutSkuId" />
            <el-table-column align="center" label="视频号商品Id" prop="liveProductId" />
            <el-table-column align="center" label="视频号skuId" prop="liveSkuId" />
            <el-table-column align="center" label="售卖价格" prop="salePrice" />
            <el-table-column align="center" label="市场价格" prop="marketPrice" />
            <el-table-column align="center" label="创建时间" prop="createTime" />

            <el-table-column align="center" label="更新时间" prop="updateTime" />
          </el-table>
        </template>
      </el-table-column>

      <el-table-column align="center" label="鲸致商品id" prop="jzGoodsId">
        <template slot-scope="scope">
          <el-button
            type="text"
            @click="linkGoodsDetail(scope.row.jzGoodsId)"
          >{{ scope.row.jzGoodsId }}</el-button>
        </template>
      </el-table-column>
      <el-table-column align="left" label="对外商品编号" prop="jzOutProductId" />
      <el-table-column align="left" label="商品名称" prop="jzGoodsName" />

      <el-table-column align="center" label="视频号商品Id" prop="liveProductId" />
      <el-table-column align="left" label="版本号" prop="verId" />
      <el-table-column align="center" label="备注" prop="remark" />
      <el-table-column align="center" label="草稿状态" prop="editStatus">
        <template slot-scope="scope">
          <el-tag :type="scope.row.editStatus==4?'success':'warning'">
            {{
            scope.row.editStatus | editStatusFilter
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="线上状态" prop="status">
        <template slot-scope="scope">
          <el-tag :type="scope.row.status==5?'success':'warning'">
            {{
            scope.row.status | statusFilter
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="审核信息" prop="resultMsg" />

      <el-table-column align="center" label="首次提交时间" prop="createTime" />
      <el-table-column align="center" label="最近更新时间" prop="updateTime" />
      <el-table-column
        align="center"
        label="操作"
        class-name="small-padding fixed-width"
        fixed="right"
        width="240"
      >
        <template slot-scope="scope">
          <el-button type="success" size="mini" @click="handleEdit(scope.row)" plain v-permission="['POST /admin/localLive/updateLiveGoods']">编辑</el-button>
          <el-button type="success" size="mini" @click="handleRefresh(scope.row)" plain v-permission="['GET /admin/localLive/refreshStatus']">刷新状态</el-button>
            <el-button v-permission="['GET /admin/localLive/delete']" type="danger" size="mini" @click="handleDelete(scope.row)" plain v-if="!scope.row.deleted">删除</el-button>
          <el-switch
            v-model="scope.row.status"
            active-text="上架"
            inactive-text="下架"
            v-if="scope.row.editStatus==4&&(scope.row.status==0||scope.row.status==5||scope.row.status==11)"
            @change="operGoodsStatus(scope.row)"
            :active-value="5"
            :inactive-value="0||11"
            v-permission="['GET /admin/localLive/spuListing']"
          />
          
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.limit"
      @pagination="getList"
    />

    <!-- 录入 -->
    <el-dialog
      :visible.sync="dialogFormVisible"
      :title="diaType==1?'新建视频号商品':'编辑视频号商品'"
      width="700px"
      center
    >
      <el-form
        ref="dataForm"
        :model="dataForm"
        :rules="dataFormRules"
        status-icon
        label-position="right"
        label-width="100px"
        style=" padding:10px 30px"
      >
        <el-row :gutter="60">
          <el-col :span="24">
            <el-form-item label="选择商品" prop="jzGoodsId" v-if="diaType==1">
              <el-cascader
                v-model="dataForm.jzGoodsId"
                :options="goodsList"
                expand-trigger="hover"
                style="width:100%"
                clearable
                @change="handleTypeChange"
                class="filter-item"
                placeholder="请选择商品"
              ></el-cascader>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="60" v-if="diaType==2">
          <el-col :span="24">
            <el-form-item label="商品名称" prop="name">
              <el-input disabled v-model="dataForm.name" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="60">
          <el-col :span="24">
            <el-form-item label="规格" prop="productIdList">
              <el-select
                v-model="dataForm.productIdList"
                style="width:100%"
                placeholder="请选择规格"
                multiple
              >
                <el-option
                  v-for="item in skuList"
                  :key="item.id"
                  :label="item.specifications[0]+' (售卖价格：'+item.price+')'"
                  :value="item.id"
                />
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="60">
          <el-col :span="24">
            <el-form-item label="版本号" prop="version">
              <el-input v-model="dataForm.version" clearable />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="60">
          <el-col :span="24">
            <el-form-item label="备注" prop="remark">
              <el-input v-model="dataForm.remark" clearable />
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmInsert">确定</el-button>
      </div>
    </el-dialog>

  </div>
</template>

<script>
import {
  getProduct,
  listGoods3,
  liveGetGoodsList,
  liveAddLocalLiveGoods,
  liveUpdateLiveGoods,
  liveGetGoodsProduct,
  liveRefreshStatus,
  liveSpuListing,
  liveDelete
} from "@/api/goods";
import { allChannel } from "@/api/channel";
import Pagination from "@/components/Pagination"; // Secondary package based on el-pagination
import { formatDate } from "@/utils/date";
import checkPermission from "@/utils/permission"; // 权限判断函数

let vm;
export default {
  name: "Order",
  components: { Pagination },
  filters: {
    channelsFilter(value) {
      const rs = vm.channels.filter(item => {
        return item.id === value;
      });
      if (rs != null && rs.length > 0) {
        return rs[0].name;
      }
    },
    statusFilter(value) {
      //'0初始值\n,5上架\n，11自主下架，\n13违规下架/风控系统下架\n
      if (value == "0") {
        return "初始值";
      } else if (value == "5") {
        return "上架";
      } else if (value == "11") {
        return "自主下架";
      } else if (value == "13") {
        return "违规下架/风控系统下架";
      } else return "";
    },
    editStatusFilter(value) {
      //：0初始值\n,1(编辑中)未审核,2审核中,3审核失败,4审核成功\n
      if (value == "0") {
        return "初始值";
      } else if (value == "1") {
        return "未审核";
      } else if (value == "2") {
        return "审核中";
      } else if (value == "3") {
        return "审核失败";
      } else if (value == "4") {
        return "审核成功";
      } else return "";
    }
  },
  data() {
    return {
      diaType: 1, //1,新建 2编辑
      goodsList: [],
      skuList: [],
      dialogFormVisible: false,
      list: [],
      total: 0,
      listLoading: true,
      listQuery: {
        page: 1,
        limit: 20,
        jzGoodsId: "",
        liveProductId: ""
      },
      channels: [],
      dataForm: {
        jzGoodsId: [],
        goodsValue: "",
        productIdList: [],
        version: "",
        remark: ""
      },
      dataFormRules: {
        version: [{ required: true, message: "请输入版本号", trigger: "blur" }],
        name: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
        jzGoodsId: [
          { required: true, message: "请选择商品", trigger: "change" }
        ],
        productIdList: [
          { required: true, message: "请选择规格", trigger: "change" }
        ]
      }
    };
  },
  computed: {},
  beforeCreate() {
    vm = this;
  },
  created() {
    this.getList();
    this.handleListGoods();
  },
  methods: {
    checkPermission,
    handleListGoods() {
      listGoods3({ channelId: 5 })
        .then(res => {
          console.info(res);
          this.goodsList = res.data.data.goodsList;
        })
        .catch(() => {});
    },
    handleExpandChange(row, expandRows) {
      if (!row.isLoadGoodDetail) {
        liveGetGoodsProduct({ jzGoodsId: row.jzGoodsId }).then(res => {
          let list = res.data.data;
          row.externalList = list;
          console.log(row.externalList);
          // this.$forceUpdate();
        });
        row.sLoadGoodDetail = true;
      }
    },
    handleRefresh(row) {
      this.$confirm("确定刷新吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        liveRefreshStatus({ liveProductId: row.liveProductId })
          .then(response => {
            this.$notify.success({
              title: "成功",
              message: "刷新成功"
            });
            this.getList();
          })
          .catch(response => {
            this.$notify.error({
              title: "失败",
              message: response.data.errmsg
            });
          });
      });
    },
    handleEdit(row) {
      this.diaType = 2;
      this.dialogFormVisible = true;
      this.dataForm = {
        name: row.jzGoodsName,
        goodsValue: row.jzGoodsId,
        liveProductId: row.liveProductId,
        productIdList: row.productIdList,
        version: row.verId,
        remark: row.remark
      };
      getProduct({ goodsId: this.dataForm.goodsValue }).then(res => {
        this.skuList = res.data.data;
      });
    },
    handleTypeChange(value) {
      console.log(value);
      this.dataForm.goodsValue = ""; //
      if (value.length > 0) {
        this.dataForm.goodsValue = value[value.length - 1];

        getProduct({ goodsId: this.dataForm.goodsValue }).then(res => {
          this.skuList = res.data.data;
        });
      }
      console.log(this.dataForm.goodsValue);
    },
    goodsIdChange(value) {
      this.listQuery.goodsId = ""; //
      if (value.length > 0) {
        this.listQuery.goodsId = value[value.length - 1];
      }
      console.log(this.listQuery.goodsId);
    },
    getList() {
      liveGetGoodsList(this.listQuery)
        .then(response => {
          let list = response.data.data.list;
          this.list = list.map(item => {
            let obj = item;
            obj.externalList = [];
            obj.sLoadGoodDetail = false;
            return obj;
          });
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    handleCreate() {
      this.dataForm = {
        jzGoodsId: [],
        goodsValue: "",
        productIdList: [],
        version: "",
        remark: ""
      };
      this.diaType = 1;
      this.dialogFormVisible = true;
      this.$nextTick(() => {
        this.$refs["dataForm"].clearValidate();
      });
    },

    formatTime(time) {
      if (time == null || time === "") {
        return "";
      }
      const date = new Date(time);
      return formatDate(date, "yyyy-MM-dd hh:mm:ss");
    },
    handleFilter() {
      this.listQuery.page = 1;
      this.getList();
    },


  
 
    operGoodsStatus(row) {
      console.log(row); //1上架 2下架
      let operType = row.status == 5 ? 1 : 2;
      let operStr=operType==1?'上架':'下架';

         this.$confirm(`确定${operStr}吗?`, "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        liveSpuListing({ liveProductId: row.liveProductId, operType: operType })
        .then(response => {
          this.$notify.success({
            title: "成功",
            message: "商品上下架设置成功"
          });
        })
        .catch(response => {
          this.$notify.error({
            title: "失败",
            message: response.data.errmsg
          });
          this.getList();
        });
      });
     
    },
    linkGoodsDetail(id) {
      this.$router.push({ path: "/goods/edit", query: { id: id } });
    },
    confirmInsert() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          const loading = this.$loading({
            lock: true,
            text: "正在保存数据，请稍后...",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.5)",
          });
          if (this.diaType == 1) {
            liveAddLocalLiveGoods({
              jzGoodsId: this.dataForm.goodsValue,
              productIdList: this.dataForm.productIdList,
              version: this.dataForm.version,
              remark: this.dataForm.remark
            })
              .then(response => {
                loading.close();
                this.dialogFormVisible = false;
                this.$notify.success({
                  title: "成功",
                  message: "添加成功"
                });
                this.getList();
              })
              .catch(response => {
                loading.close();
                this.$notify.error({
                  title: "添加失败",
                  message: response.data.errmsg
                });
              });
          } else {
            liveUpdateLiveGoods({
              jzGoodsId: this.dataForm.goodsValue,
              liveProductId: this.dataForm.liveProductId,
              productIdList: this.dataForm.productIdList,
              version: this.dataForm.version,
              remark: this.dataForm.remark
            })
              .then(response => {
                loading.close();
                this.dialogFormVisible = false;
                this.$notify.success({
                  title: "成功",
                  message: "编辑成功"
                });
                this.getList();
              })
              .catch(response => {
                loading.close();
                this.$notify.error({
                  title: "编辑失败",
                  message: response.data.errmsg
                });
              });
          }
        }
      });
    },
    handleDelete(row) {
        this.$confirm("商品删除后无法恢复，确定继续删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
         liveDelete({ jzGoodsId: row.jzGoodsId })
        .then(response => {
          this.$notify.success({
            title: "成功",
            message: "删除成功"
          });
          this.getList();
        })
        .catch(response => {
          this.$notify.error({
            title: "失败",
            message: response.data.errmsg
          });
        });
      });
    }





  }
};
</script>

<style>
.detail-container {
  width: 80%;
  padding: 20px 20px 20px 20px;
  margin: 20px auto;
}

.operate-container {
  background: #f2f6fc;
  height: 80px;
  margin: -20px -20px 0;
  line-height: 80px;
}

.operate-button-container {
  float: right;
  margin-right: 20px;
}

.table-layout {
  margin-top: 20px;
  border-left: 1px solid #dcdfe6;
  border-top: 1px solid #dcdfe6;
}

.table-cell {
  height: 60px;
  line-height: 20px;
  border-right: 1px solid #dcdfe6;
  border-bottom: 1px solid #dcdfe6;
  padding: 10px;
  font-size: 14px;
  color: #606266;
  text-align: center;
  white-space: pre-wrap;
  /* overflow: hidden; */
}

.table-cell-title {
  border-right: 1px solid #dcdfe6;
  border-bottom: 1px solid #dcdfe6;
  padding: 10px;
  background: #f2f6fc;
  text-align: center;
  font-size: 14px;
  color: #303133;
}

.el-table th.gutter {
  display: table-cell !important;
}

.color-danger {
  color: #f56c6c;
  font-size: 18px;
}

.el-dialog .el-cascader {
  width: 400px;
}

.fixed-width .el-button--mini {
  width: auto;
  min-width: 60px;
  margin-bottom: 8px;
}
</style>
