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

      <!-- <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.goodsId" :options="goodsList" expand-trigger="hover" style="width:400px" clearable
        class="filter-item" placeholder="请选择商品" @change="goodsIdChange" />

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

      <el-button v-permission="['POST /admin/goodsExternal/insert']" 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>
<!--      <el-table-column align="center" type="expand" prop="id" fixed="left">-->
<!--        <template slot-scope="scope">-->
<!--          <el-table :data="scope.row.externalList" style="width:1150px" border fit highlight-current-row>-->
<!--            <el-table-column align="center" label="门店" width="150" prop="shopName" />-->
<!--            <el-table-column align="center" label="门店地址" width="150" prop="shopAddress" />-->
<!--            <el-table-column align="center" label="申请时间" width="180" prop="createTime" />-->
<!--           <el-table-column align="center" label="状态" width="150" prop="isUse">-->
<!--              <template slot-scope="scope">-->
<!--                <el-tag type="warn">-->
<!--                  {{ scope.row.isUse==1?"启用":"停用" }}-->
<!--                </el-tag>-->
<!--              </template>-->
<!--            </el-table-column>-->
<!--             <el-table-column align="center" label="更新时间" prop="updateTime" />-->

<!--          </el-table>-->
<!--        </template>-->
<!--      </el-table-column>-->

      <el-table-column align="center" label="商品id" prop="goodsId" width="100">
        <template slot-scope="scope">
          <el-button type="text" @click="linkGoodsDetail(scope.row.goodsId)">{{ scope.row.goodsId }}</el-button>
        </template>
      </el-table-column>
      <el-table-column align="left" label="商品名称" prop="goodsName" width="320">
        <template slot-scope="scope">
            <div style="text-align: left;">
              <span style="font-weight: 600;">商品名称:</span> {{ scope.row.goodsName }}<br/>
              <span style="font-weight: 600;">版本号:</span> {{ scope.row.version }}<br/>
              <span style="font-weight: 600;">版本说明:</span> {{ scope.row.remark }}<br/>
              <span style="font-weight: 600;">上线城市信息</span> 城市:{{ scope.row.goodsCity?scope.row.goodsCity:0 }}个 门店:{{ scope.row.goodsShops?scope.row.goodsShops:0 }}个<br/>
            </div>
        </template>
      </el-table-column>
      <el-table-column align="left" label="商品名称" prop="goodsName">
        <template slot-scope="scope">
            <div style="text-align: left;">
             <span style="font-weight: 600;">抖音商品Id:</span> {{ scope.row.oddGoodsNo }}<br/>
              <span style="font-weight: 600;">审核状态:</span>
              <el-tag :type="scope.row.dyAuditStatus==1?'success':'warning'">{{scope.row.dyAuditStatus | dyStatusFilter}}</el-tag><br/>
              <span style="font-weight: 600;">审核反馈信息:</span><span> {{ scope.row.dyAuditMsg }}</span><br/>
            </div>
        </template>
      </el-table-column>

      <!-- <el-table-column align="center" label="抖音商品Id" prop="oddGoodsNo" />
      <el-table-column align="center" label="审核状态" prop="dyAuditStatus">
        <template slot-scope="scope">
          <el-tag :type="scope.row.dyAuditStatus==1?'success':'warning'">
            {{
              scope.row.dyAuditStatus | dyStatusFilter
            }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column align="center" label="抖音审核反馈信息" width="120" prop="dyAuditMsg" show-overflow-tooltip/>
      <el-table-column align="center" label="上线城市及门店数" prop="goodsCity" >
        <template slot-scope="scope">
          城市:{{ scope.row.goodsCity?scope.row.goodsCity:0 }}个 门店:{{ scope.row.goodsShops?scope.row.goodsShops:0 }}个
        </template>
      </el-table-column>-->
      <el-table-column align="center" label="操作时间" prop="createTime"  width="260px">
        <template slot-scope="scope">
            <div style="text-align: left;">
              <span style="font-weight: 600;">首次提交时间:</span> {{ scope.row.createTime }}<br/>
              <span style="font-weight: 600;">最近更新时间:</span> {{ scope.row.updateTime }}<br/>
            </div>
        </template>
      </el-table-column>
      <!-- <el-table-column align="center" label="最近更新时间" prop="updateTime" /> -->
      <el-table-column align="center" label="操作" class-name="small-padding fixed-width" fixed="right" width="160">
        <template slot-scope="scope">
          <!-- <el-button v-permission="['GET /admin/goodsExternal/delete']" type="danger" size="mini" @click="handleDeleteConfirm(scope2.row)">删除</el-button> -->
          <!-- <el-button type="primary" size="mini" @click="updateGoodsInfo(scope.row)" v-if="scope.row.goodsSn != scope.row.oddGoodsNo">更新抖音侧商品信息</el-button> -->
          <!-- <el-button type="success" v-if="scope.row.dyAuditStatus == 1" size="mini" @click="handleQrCode(scope.row)">生成抖音二维码</el-button> -->
          <el-switch v-model="scope.row.isOnTheSelf" active-text="上架" inactive-text="下架"
            @change="operGoodsStatus(scope.row)" :active-value="1" :inactive-value="2" v-if="scope.row.goodsSn != scope.row.oddGoodsNo" />
        </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="外部商品配置" width="700px" center>
      <el-form ref="dataForm" :model="dataForm" :rules="dataFormRules" status-icon label-position="left"
        label-width="160px" style=" padding:10px 30px">
        <el-row :gutter="60">
          <el-col :span="24">
            <el-form-item label="外部商品编号" prop="oddGoodsNo">
              <el-input v-model="dataForm.oddGoodsNo" clearable />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="60">
          <el-col :span="24">
            <el-form-item label="选择商品" prop="goodsId">
              <el-cascader v-model="dataForm.goodsId" :options="goodsList" expand-trigger="hover" style="width:100%"
                clearable @change="handleTypeChange" class="filter-item" placeholder="请选择商品" />
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="订单渠道" prop="channelId">
              <el-select v-model="dataForm.channelId" style="width:100%" placeholder="请选择" filterable>
                <el-option v-for="item in channels" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>
            </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>

    <!-- 二维码 -->
    <el-dialog :visible.sync="dialogQrCodeVisible" title="抖音商品二维码" width="700px" center>
      <el-image :src="qrCodeUrl"></el-image>
    </el-dialog>


  </div>
</template>

<script>
import {
  goodsExternalDel,
  goodsExternalInsert,
  goodsExternalList,
  listGoods3,
  operGoodsStatus,
  updateGoodsInfo,
  goodsDYQrcode
} 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;
      }
    },
    dyStatusFilter(value) {
      ///10 审核中 11 审核通过(旧) 1审核通过(新) 12 审核拒绝 21 商家拒绝 22 商家确认通过 23 商家确认超时
      if (value === "10") {
        return "审核中";
      } else if (value === "12") {
        return "审核拒绝";
      } else if (value === "1") {
        return '审核通过';
      }
      else return '待提交审核';
    }
  },
  data() {
    return {
      goodsList: [],
      dialogFormVisible: false,
      list: [],
      total: 0,
      listLoading: true,
      dialogQrCodeVisible: false,
      qrCodeUrl: '',//抖音二维码
      listQuery: {
        page: 1,
        limit: 20,
        goodsId: "",
        channelId: "",
        dyAuditStatus: "",
        oddGoodsNo: "",
        sort: "create_time",
        order: "desc"
      },
      channels: [],
      dataForm: {
        goodsId: "",
        channelId: "",
        oddGoodsNo: "",
      },
      dataFormRules: {

        oddGoodsNo: [
          { required: true, message: "请输入外部商品编号", trigger: "blur" }
        ],
        goodsId: [{ required: true, message: "请选择商品", trigger: "change" }],
        channelId: [
          { required: true, message: "请选择渠道", trigger: "change" }
        ],

      }
    };
  },
  computed: {},
  beforeCreate() {
    vm = this;
  },
  created() {
    this.getList();
    allChannel().then(res => {
      this.channels = res.data.data;
    });
    this.handleListGoods();
  },
  methods: {
    checkPermission,
    handleListGoods() {
      listGoods3({ channelId: 26 })
        .then(res => {
          console.info(res);
          this.goodsList = res.data.data.goodsList;
        })
        .catch(() => {
        });
    },
    handleQrCode(row) {
      goodsDYQrcode({ goodsId: row.goodsId }).then(res => {
        this.dialogQrCodeVisible = true;
        this.qrCodeUrl = res.data.data;
      })
    },
    handleTypeChange(value) {
      this.dataForm.goodsValue = '';//
      if (value.length > 0) {
        this.dataForm.goodsValue = (value[value.length - 1]);
      }
      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() {
      goodsExternalList(this.listQuery)
        .then(response => {
          this.list = response.data.data.list;
          this.total = response.data.data.total;
          this.listLoading = false;
        })
        .catch(() => {
          this.list = [];
          this.total = 0;
          this.listLoading = false;
        });
    },
    handleCreate() {
      this.dataForm = {
        goodsId: '',
        channelId: '',
        oddGoodsNo: ''
      }
      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();
    },


    handleDeleteConfirm(row) {
      this.$confirm("商品删除后无法恢复，确定继续删除吗?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.handleDelete(row);
      });
    },
    handleDelete(row) {
      goodsExternalDel({ id: row.id })
        .then(response => {
          this.$notify.success({
            title: "成功",
            message: "删除成功"
          });
          this.getList();
        })
        .catch(response => {
          this.$notify.error({
            title: "失败",
            message: response.data.errmsg
          });
        });
    },
    updateGoodsInfo(row) {
      console.log(row);
      updateGoodsInfo({ goodsId: row.goodsId, shopNo: row.shopNo })
        .then((response) => {
          this.$notify.success({
            title: "成功",
            message: "编辑成功",
          });
        })
        .catch((response) => {
          this.$notify.error({
            title: "失败",
            message: response.data.errmsg,
          });

        });
    },
    operGoodsStatus(row) {
      console.log(row);
      let operType = (row.isOnTheSelf
        == 2 ? 2 : 1);
      console.log(operType);
      operGoodsStatus({ goodsId: row.goodsId, operType: operType, channelId: row.channelId })
        .then((response) => {
          this.$notify.success({
            title: "成功",
            message: "商品上下架设置成功",
          });


        })
        .catch((response) => {
          this.$notify.error({
            title: "失败",
            message: response.data.errmsg,
          });
          row.isOnTheSelf = (row.isOnTheSelf == 1 ? 2 : 1);
        });
    },
    linkGoodsDetail(id) {
      this.$router.push({ path: "/goods/edit", query: { id: id } });
    },
    confirmInsert() {
      this.$refs["dataForm"].validate(valid => {
        if (valid) {
          goodsExternalInsert({
            goodsId: this.dataForm.goodsValue,
            channelId: this.dataForm.channelId,
            oddGoodsNo: this.dataForm.oddGoodsNo,
          })
            .then(response => {
              this.dialogFormVisible = false;
              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>
