<!--
 * @Author: xiachao 958053195@qq.com
 * @Date: 2024-05-13 14:20:24
 * @LastEditors: xiachao 958053195@qq.com
 * @LastEditTime: 2024-05-26 00:37:01
 * @FilePath: \ruoyi-ui\src\views\order\jldetail.vue
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
-->
<template>
  <div class="jlDetail order-index">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="mini"
      :inline="true"
      v-show="showSearch"
      class="mini-form"
      label-width="90px"
    >
      <el-form-item label="品牌:" prop="brandCode">
        <el-select
          multiple
          v-model="queryParams.brandCode"
          filterable
          placeholder="品牌"
          clearable
          style="width: 155px;"
        >
          <el-option
            v-for="(dict, index) in brandNameList"
            :key="index"
            :label="dict.brandName"
            :value="dict.brandCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="类目:" prop="categoryCode">
        <el-select
        multiple
          v-model="queryParams.categoryCode"
          filterable
          style="width: 155px;"
          placeholder="类目"
          clearable
        >
          <el-option
            v-for="(dict, index) in categoryList"
            :key="index"
            :label="dict.categoryName"
            :value="dict.categoryCode"
          />
        </el-select>
      </el-form-item>

      <el-form-item label="商品编码:" prop="skuNos2">
        <el-input
          v-model="queryParams.skuNos2"
          style="width: 155px;"
          placeholder="多个商品编码使用逗号隔开"
          @input="value=>copySkus(value,'skuNos2')"
          clearable
        />
      </el-form-item>
      <el-form-item label="商品名称:" prop="skuNo">
        <LoadMoreSelect
          :skuNo="queryParams.skuNo"
          style="width: 155px;"
          @queryParams="(val) => (queryParams.skuNo = val)"
        />
      </el-form-item>
      <!-- <el-row :gutter="10" class="mb8" type="flex" justify="end"> -->
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery"
            >搜索</el-button
          >
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery"
            >重置</el-button
          >
        </el-form-item>
      <!-- </el-row> -->
    </el-form>

    <el-row :gutter="10" class="mb8" >
      <el-col :span="1.5" style="height: 30px;display: flex;align-item: center;">
        <el-radio v-model="radio" label="1">竞价抢单</el-radio>
        <el-radio v-model="radio" label="2">指定供货商代发</el-radio>
        <el-select
          v-show="radio=='2'"
          v-model="supplierCode"
          size="mini"
          filterable
          style="width: 175px;"
          placeholder="请选择供货商"
          clearable
        >
          <el-option
            v-for="(dict, index) in supplierList"
            :key="index"
            :label="dict.supplierName"
            :value="dict.supplierCode"
          />
        </el-select>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>


    <el-table ref="logTable" header-cell-class-name="all-select" v-loading="tableLoading" :cell-style="cellStyle"
    border :data="tableList" @selection-change="handleSelectionChange" @select="handleSelection"

    >
      <el-table-column type="selection" width="55" align="center" :selectable="selectable"  />
      <el-table-column
        label="平台订单号"
        min-width="110"
        align="left"
        fixed="left"
        prop="platformCode"
      />
      <el-table-column label="店铺" min-width="90" align="left" prop="shopName" />
      <el-table-column label="品牌/类目" min-width="100" align="left" prop="shopName">
        <template slot-scope="scope">
          {{ scope.row.brandName }}/{{ scope.row.categoryName }}
        </template>
      </el-table-column>
      <!-- <el-table-column
        label="销售部门"
        min-width="100"
        align="left"
        prop="deptName"
      /> -->
      <el-table-column
        label="商品信息"
        min-width="190"
        align="left"
        prop="createTime"
      >
        <template slot-scope="scope">
          {{ scope.row.skuName }}/{{ scope.row.skuNo }}
        </template>
      </el-table-column>
      <el-table-column
        label="管易库存"
        min-width="130"
        align="left"
        prop="createTime"
      >
        <template slot-scope="scope">
          <div v-for="(item,index) in scope.row.erpInStocks" v-show="item.qty" :key="index">
            {{ item.warehouseName }} &nbsp; {{ item.qty }}件
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="代发数量"
        min-width="75"
        align="left"
        prop="qty"
      />
      <el-table-column
        label="湘商成本价"
        min-width="110"
        align="left"
        v-if="radio=='2'"
        prop="qty"
      >
        <template slot-scope="scope">
          <div v-for="(item,index) in scope.row.warehousePrices" v-show="item.price" :key="index">
            {{ item.warehouseName }} &nbsp; {{ item.price }}元
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="代发价格"
        min-width="120"
        align="left"
        v-if="radio=='2'"
        prop="qty"
      >
        <template slot="header" slot-scope="scope">
          <div class="table-head">代发价格</div>
          <el-input size="mini" style="width: 65px;" type="number" v-model="guidePrice"></el-input>
          <el-button type="text" size="mini" @click="handlePrice"
            >应用</el-button
          >
        </template>
        <template slot-scope="scope">
          <el-input size="mini" type="number" v-model="scope.row.guidePrice"></el-input>
        </template>
      </el-table-column>
      <el-table-column
        label="聚链代发价格"
        min-width="140"
        align="left"
        prop="createTime"
      >
        <template slot-scope="scope">
          <div v-show="scope.row.julianPriceList.stage1Price">
            <span><span class="julianPrice">价1</span> {{ scope.row.julianPriceList.stage1Price }};</span>
            <span><span class="julianPrice">价2</span>  {{ scope.row.julianPriceList.stage2Price }};</span>
            <span><span class="julianPrice">价3</span>  {{ scope.row.julianPriceList.stage3Price }};</span>
            <span><span class="julianPrice">价4</span>  {{ scope.row.julianPriceList.stage4Price }};</span>
          </div>

          <div v-show="!scope.row.julianPriceList.stage1Price">
            <div class="no-price">无</div>
            <div class="set-price" @click="setPrice(scope.row)">去设置</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="市场参考价格"
        min-width="110"
        align="left"
        prop="createTime"
      >
        <template slot-scope="scope">
          <div class="goProcure"  @click="goProcure(item.url)" v-for="(item,index) in scope.row.marketPrice" :key="index">
            {{ item.name }}:{{ item.price }}
          </div>
        </template>
      </el-table-column>
      <el-table-column
        label="备注"
        min-width="120"
        align="left"
        prop="remark"
      >
        <template slot-scope="scope">
          <el-tooltip class="item" content="Top center" placement="top">
            <div slot="content" style="width: auto">{{ scope.row.remark }}</div>
            <div class="table-overflow">{{ scope.row.remark }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column
        label="近7天成交价格"
        min-width="70"
        align="center"
        prop="sevenDayAvgPrice"
      />
      <el-table-column
        label="收货人"
        min-width="70"
        align="left"
        prop="receiverName"
      />
      <el-table-column
        label="联系方式"
        min-width="90"
        align="left"
        prop="receiverPhone"
      />
      <el-table-column
        label="收货地址"
        min-width="160"
        align="left"
        prop="receiverAddress"
      >
        <template slot-scope="scope">
          <el-tooltip class="item" content="Top center" placement="top">
            <div slot="content" style="width: auto">{{ scope.row.receiverAddress }}</div>
            <div class="table-overflow">{{ scope.row.receiverAddress }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
    </el-table>
    <div class="total">总计 {{ tableList.length }}条 订单商品行</div>
    <div class="warning-alert">
      注意：<br/>
      1,未设置聚链代发价格的订单商品无法代发<br/>
      2,已配货，已发货的订单无法代发
    </div>
    <div slot="footer" class="dialog-footer">
      <el-button :loading="submitLoading" type="primary" @click="submitFileForm">推送</el-button>
      <el-button @click="closeDia">关闭</el-button>
    </div>
  </div>
</template>

<script>
import {getBrandNameList,} from "@/api/goods/index";
import {getCategory, needJulianSend, pushJulianSend, queryJulianSupplier, queryNeedJulianSend} from '@/api/order/index';
import LoadMoreSelect from "@/components/LoadMoreSelect/index";

export default {
  name: "Jldetail",
  components: {
    LoadMoreSelect
  },
  props: {
    // ids: {
    //   type: Array,
    //   default: []
    // }
  },
  data() {
    return {
      tableList: [],
      pushList: [],
      categoryList: [],
      guidePrice: 0,
      showSearch: true,
      supplierCode: '',
      radio: '1',
      submitLoading: false,
      queryParams: {
        "brandCode": [],
        categoryCode: [],
        "orderId": [],
        "skuNo": "",
        "skuNos": []
      },
      ids: '',
      brandNameList:[],
      tableLoading: false,
      firstTime: true,
      supplierList: []
    };
  },
  created() {
    this.ids = JSON.parse(sessionStorage.getItem('Jldetail-ids'));
    this.getDict();
    this.getList();
  },
  activated() {
    if(this.firstTime){ return false }
    if(JSON.parse(sessionStorage.getItem('Jldetail-ids'))){
      const idss = sessionStorage.getItem('Jldetail-ids');
      if(JSON.stringify(this.ids) != idss){
        this.ids = JSON.parse(sessionStorage.getItem('Jldetail-ids'));
        this.getList();
      }
    }

  },
  methods: {
    copySkus(value,row){
        this.$set(this.queryParams,row,value.trim().split(/\s+/).join(','))
    },
    handlePrice(){
      this.tableList.forEach(item=>{
        item.guidePrice = this.guidePrice;
      })
    },
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        "brandCode": [],
        categoryCode: [],
        "orderId": [],
        "skuNo": "",
        "skuNos": []
      };
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.getList();
    },
    getDict(){
      getBrandNameList().then((res) => {
        this.brandNameList = res.data;
      });
      queryJulianSupplier().then(res=>{
        if(res.status==200){
          this.supplierList = res.data;
        }
      });
      getCategory().then((res) => {
        if(res.status==200){
          this.categoryList = res.data || [];
        }
      });
    },
    selectable(row, index){
      return row.checked;
      // return true;
    },
    goProcure(url){
      // this.$router.push({
      //   path: url
      // });
      window.open(url)
    },
    getList(){
      let data = {};
      if(this.queryParams.skuNos2){
        this.queryParams.skuNos = this.queryParams.skuNos2.split(',');
      }else{
        this.queryParams.skuNos = [];
      }
      data = Object.assign(data, this.queryParams);
      if(this.ids[0]&&this.ids[0].skuNo){
        data.orders = this.ids;
        this.tableLoading = true;
        needJulianSend(data).then(res=>{
          if(res.status == 200){
            // this.tableList = res.data;
            this.tableList = [];
            // console.log(this.sortClass(res.data))
            const sortClass = this.sortClass(res.data);
            sortClass.forEach((item,index)=>{
              for(let i=0;i<item.length;i++){
                if(item[i].checked){
                  item[i].checks = true;
                  break;
                }
              }
              if(index % 2 == 0){
                for(let i=0;i<item.length;i++){
                  item[i].background = 'background: rgb(247, 250, 255);';
                }
              }else{
                for(let i=0;i<item.length;i++){
                  item[i].background = 'background: rgb(242, 251, 238);';
                }
              }
              this.tableList = this.tableList.concat(item);
            });

            this.$nextTick(() => {
              for (const row of this.tableList) {
                // row.guidePrice = 0;
                this.$set(row,'guidePrice',0)
                if(row.checks){
                  this.$refs.logTable.toggleRowSelection(row, true);
                }
              }
            })
          }
          this.tableLoading = false;
          this.firstTime = false
        }).catch(err=>{
          this.tableLoading = false;
          this.firstTime = false;
        })
      }else{
        data.orderId = this.ids;
        this.tableLoading = true;
        queryNeedJulianSend(data).then(res=>{
          if(res.status == 200){
            // this.tableList = res.data;
            this.tableList = [];
            // console.log(this.sortClass(res.data))
            const sortClass = this.sortClass(res.data);
            sortClass.forEach((item,index)=>{
              for(let i=0;i<item.length;i++){
                if(item[i].checked){
                  item[i].checks = true;
                  break;
                }
              }
              if(index % 2 == 0){
                for(let i=0;i<item.length;i++){
                  item[i].background = 'background: rgb(247, 250, 255);';
                }
              }else{
                for(let i=0;i<item.length;i++){
                  item[i].background = 'background: rgb(242, 251, 238);';
                }
              }
              this.tableList = this.tableList.concat(item);
            });

            this.$nextTick(() => {
              for (const row of this.tableList) {
                // row.guidePrice = 0;
                this.$set(row,'guidePrice',0)
                if(row.checked){
                  this.$refs.logTable.toggleRowSelection(row, true);
                }
              }
            })
          }
          this.tableLoading = false;
          this.firstTime = false
        }).catch(err=>{
          this.tableLoading = false;
          this.firstTime = false;
        })
      }


    },
    sortClass(sortData){
      const groupBy = (array, f) => {
        let groups = {};
        array.forEach((o) => {
          let group = JSON.stringify(f(o));
          groups[group] = groups[group] || [];
          groups[group].push(o);
        });
        return Object.keys(groups).map((group) => {
          return groups[group];
        });
      };
      const sorted = groupBy(sortData, (item) => {
        return item.platformCode; // 返回需要分组的对象
      });
      return sorted;
    },
    handleSelectionChange(selection){
      this.pushList = selection;
    },
    handleSelection(selection,row){
    //  this.tableList.forEach(item=>{
      //  if(item.platformCode==row.platformCode&&item.skuNo!=row.skuNo){
      //    this.$refs.logTable.toggleRowSelection(item, false);
      //  }
      //})
    },
    submitFileForm(){
      if(this.pushList.length==0){
        this.$message.warning('请选择单据');
        return false;
      }
      let supplierData = {}
      if(this.radio=='2'){
        if(this.supplierCode==''){
          this.$message.warning('请选择供货商');
          return false;
        }
        supplierData = this.supplierList.find(item=>{
          return item.supplierCode == this.supplierCode;
        });

        let status = true;
        for(let i=0;i<this.pushList.length;i++){
          this.pushList[i].supplierCode = supplierData.supplierCode;
          this.pushList[i].supplierName = supplierData.supplierName;
          if(this.pushList[i].guidePrice==0||this.pushList[i].guidePrice==''){
            status = false;
          }
        }
        if(!status){
          this.$message.warning('请填写代发价格');
          return false;
        }
      }

      //
      let confirm = false;
      this.$modal
          .confirm('以下订单商品聚链代发[价1]价格高于最近7天成交价格1%或高于50元：\n11111')
          .then(function () {
            confirm = true;
          })
          .catch(() => {
          });
      if (!confirm) {
        return false;
      }
      this.submitLoading = true;
      pushJulianSend(this.pushList).then(res=>{
        if(res.status==200){
          this.$message.success('推送成功');
          this.$router.back();
          // this.$emit('close',true)
        }
        this.getList();
        this.submitLoading = false;
      }).catch(err=>{
        this.getList();
        this.submitLoading = false;
      })
    },
    closeDia(){
      // this.$emit('close',true)
      this.$tab.closePage();
    },
    cellStyle(row){
      let stage1Price = row.row.julianPriceList.stage1Price;
      let sevenDayAvgPrice = row.row.sevenDayAvgPrice;
      if (stage1Price && sevenDayAvgPrice) {
        if (stage1Price - sevenDayAvgPrice >= 50 || stage1Price >= sevenDayAvgPrice * 1.01) {
          return 'background: rgb(247,186,186);'
        }
      }

    },
    setPrice(row){
      const domain = window.location.hostname;
      console.log(domain)
      if(domain=='oco.xsbuy.cn'){
        window.open("https://platform.newfirst.net/goods/goodsList?skuNo="+row.skuNo);
      }else{
        window.open("https://dev.platform.newfirst.net/goods/goodsList?skuNo="+row.skuNo);
      }
    }
  },
};
</script>
<style scoped lang="scss">
.table-head{
  font-size: 13px;
  color: #515a6e;
}
.jlDetail{
  padding: 16px;
}
.goProcure{
  color: #1890ff;
  cursor: pointer;
  font-size: 12px;
}
.dialog-footer{
  display: flex;
  justify-content: center;
  margin-top: 10px;
}
::v-deep .all-select .cell .el-checkbox__inner {
  display: none;
}
.set-price{
  color: #1890ff !important;
  cursor: pointer;
  font-size: 12px;
  display: flex;
  align-items: center;
}
.no-price{
  color: #999;
}
.julianPrice{
  color: #999;
}
.total{
  font-size: 14px;
  margin: 8px 0;
}
.warning-alert{
  background-color: #fff8e6;
  color: #ffba00;
  padding: 8px 16px;
  border-radius: 4px;
  font-size: 13px;
}
</style>
<style lang="scss">
.jlDetail{
  input[type=number]::-webkit-inner-spin-button,
  input[type=number]::-webkit-outer-spin-button {
    -webkit-appearance: none;
    margin: 0;
  }
}
</style>
