<template>
  <div class="app-container order-index" @click="closeCopy">
    <el-form
      :model="queryParams"
      ref="queryForm"
      size="mini"
      :inline="true"
      v-show="showSearch"
      class="mini-form"
      label-width="90px"
    >
      
      <el-form-item label="电商平台:" prop="platformNo">
        <el-select
          multiple
          filterable
          v-model="queryParams.platformNo"
          placeholder="请选择"
          clearable
          style="width: 155px;"
        >
          <el-option
            v-for="dict in platformLists"
            :key="dict.platformNo"
            :label="dict.platformName"
            :value="dict.platformNo"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="店铺:" prop="shopCode">
        <el-select
          multiple
          filterable
          v-model="queryParams.shopCode"
          placeholder="请选择"
          clearable
          style="width: 155px;"
        >
        <el-option
            v-for="dict in channelList"
            :key="dict.channelCode"
            :label="dict.channelName"
            :value="dict.channelCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="标记:" prop="tags">
        <el-select
          multiple
          filterable
          v-model="queryParams.tags"
          placeholder="请选择"
          clearable
          style="width: 155px;"
        >
          <el-option label="代发" value="0" />
          <el-option label="不代发" value="2" />
          <el-option label="已发货" value="1" />
        </el-select>
      </el-form-item>
      <el-form-item label="订单编码:" prop="orderNos2">
        <el-input
          v-model.trim="queryParams.orderNos2"
          placeholder="请输入平台单号/管易单号，多个逗号分隔"
          style="width: 155px;"
          clearable
          @input="value=>copySkus(value,'orderNos2')"
        />
      </el-form-item>
      <el-form-item label="品牌:" prop="brandCode">
        <el-select
          multiple
          v-model="queryParams.brandCode"
          filterable
          placeholder="品牌"
          clearable
          style="width: 155px;"
          @change="brandChange"
        >
          <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-form-item label="仓库名称:" prop="skus">
        <el-select
          multiple
          filterable
          v-model="queryParams.warehouseCode"
          placeholder="请选择仓库名称"
          style="width: 155px;"
          clearable
        >
          <el-option
            v-for="dict in warehouseLists"
            :key="dict.warehouseCode"
            :label="dict.warehouseName"
            :value="dict.warehouseCode"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="支付时间:" prop="dateRange">
        <el-date-picker
          v-model="queryParams.dateRange"
          style="width: 220px"
          value-format="yyyy-MM-dd"
          :picker-options="pickerOptions"
          type="daterange"
          range-separator="-"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          :clearable="false"
        />
      </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">
        <el-button
          type="warning"
          plain
          size="mini"
          :disabled="ids.length==0"
          @click="goJl"
          >推送聚链代发</el-button
        >
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" :columns="columns" @sort="sortCol" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table
      ref="proTable2"
      :height="tableHeight"
      border
      v-loading="loading"
      :data="postList"
      row-key="id"
      :key="randomKey"
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
      @cell-click="cellClick"
      :cell-class-name="cellClassName"
      :row-class-name="rowClassName"
    >
      <el-table-column type="selection" width="55" align="center" :reserve-selection="true" :selectable="selectable"  />

      <el-table-column v-for="(item,index) in columns" :key="index" :label="item.label" :sortable="item.sortable||false"
      :min-width="item.width||'90'" :align="item.align||'left'" :fixed="item.fixed||false" :prop="item.prop">
        <template slot-scope="scope" >
          <template v-if="item.label=='品牌/类目'">
            <el-tooltip class="item" content="Top center" placement="top">
              <div slot="content" style="width: auto">{{ scope.row.brandName }}/{{ scope.row.categoryName }}</div>
              <div class="table-overflow">{{ scope.row.brandName }}/{{ scope.row.categoryName }}</div>
            </el-tooltip>
          </template>
          <template v-else-if="item.label=='订单金额'">
            ￥{{ $numFormat(scope.row.amount) }}
          </template>
          <template v-else-if="item.label=='已配货数量'">
            {{ parseFloat(scope.row.goodNum)-parseFloat(scope.row.shortageNum) }}
          </template>
          <template v-else-if="item.label=='标记'">
            {{ scope.row.tag==0?'代发':(scope.row.tag==1?'已发货':'不代发') }}
          </template>
          
          <template v-else-if="item.label=='店铺'||item.label=='平台订单号'||item.label=='管易订单号'||item.label=='商品名称'||item.label=='品牌/类目'||item.label=='发货仓库'||item.label=='收货地址'">
            <el-tooltip class="item" content="Top center" placement="top">
              <div slot="content" style="width: auto">{{ scope.row[item.prop] }}</div>
              <div class="table-overflow">{{ scope.row[item.prop] }}</div>
            </el-tooltip>
          </template>
          <template v-else>
            {{ scope.row[item.prop] }}
          </template>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        min-width="120"
        align="center"
        fixed="right"
        prop="attrName4"
      >
      <template slot-scope="scope">
        <el-button size="mini" type="text" v-if="scope.row.tag==0" @click="updateG(scope.row, '2')">
          不代发
        </el-button>
        <el-button size="mini" type="text" v-if="scope.row.tag==2"  @click="updateG(scope.row, '0')">
          代发
        </el-button>
        <el-button size="mini" type="text" @click="showRemark(scope.row)">
          备注
        </el-button>
      </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
      class="fixed-pagination"
    />

    <!-- 添加或修改岗位对话框 -->
    <el-dialog title="修改备注" :center="true" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="remarkForm" :model="form"  label-width="0px">
        <el-form-item label="" prop="remark" :rules="[{ required: true, message: '请输入内容', trigger: 'change' }]">
          <el-input v-model="form.remark" type="textarea" :rows="4" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="open=false">取 消</el-button>
      </div>
    </el-dialog>

    <div class="chart-box" id="chart-box" ref="chartBox" v-show="contextmenuShow">
      <div @click="copyText2" class="chart-content">复制</div>
    </div>

  </div>
</template>

<script>
import {
  getBrandNameList,
  warehouseList,
} from "@/api/goods/index";
import {
  platformList,
  shortageGood,
  getCategory,
  shortageGoodUpdate
} from '@/api/order/index';
import{
  saleTargetChannelList,
} from "@/api/saleConfig/saleTarget";
import LoadMoreSelect from "@/components/LoadMoreSelect/index";
// import { getActivitieList } from "@/api/activitie/index";

export default {
  name: "OsOrder",
  components: {
    LoadMoreSelect,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 岗位表格数据
      postList: [],
      platformLists: [],
      form: {
        remark: ''
      },
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      wareHouseList: [],
      rebateTypeCodeList: [
        { code: "JLF", name: "激励返" },
        { code: "THGDF", name: "提货固定返" },
        { code: "THDLF", name: "提货达量返" },
        { code: "XSDLF", name: "销售达量返" },
        { code: "THJJTF", name: "提货价阶梯返" },
        { code: "ZDCMF", name: "指定串码返利" },
      ],
      columns: [
        {
          key: 1,
          label: '店铺',
          width: '140',
          prop: 'shopName',
          fixed: 'left',
          sortable: 'custom',
          visible: true
        },{
          key: 2,
          label: '电商平台',
          width: '100',
          prop: 'platformName',
          sortable: 'custom',
          visible: true
        },
        {
          key: 3,
          label: '平台订单号',
          width: '100',
          prop: 'platformCode',
          visible: true
        },
        {
          key: 4,
          label: '管易订单号',
          width: '100',
          prop: 'erpCode',
          visible: true
        },
        {
          key: 5,
          label: '商品编码',
          width: '110',
          prop: 'goodCode',
          sortable: 'custom',
          visible: true
        },
        {
          key: 6,
          label: '商品名称',
          width: '110',
          prop: 'goodName',
          sortable: 'custom',
          visible: true
        },
        {
          key: 7,
          label: '品牌/类目',
          width: '140',
          prop: 'brandName',
          sortable: 'custom',
          visible: true
        },
        {
          key: 8,
          label: '订单金额',
          width: '80',
          prop: 'amount',
          visible: true
        },
        {
          key: 9,
          label: '支付时间',
          width: '150',
          prop: 'payAt',
          visible: true
        },
        {
          key: 10,
          label: '购买件数',
          width: '80',
          prop: 'goodNum',
          visible: true
        },
        {
          key: 11,
          label: '已配货数量',
          width: '90',
          prop: 'productSize',
          visible: true
        },
        {
          key: 12,
          label: '缺货数量',
          width: '80',
          prop: 'shortageNum',
          visible: true
        },
        {
          key: 13,
          label: '在途数量',
          width: '80',
          prop: 'roadQty',
          visible: true
        },
        {
          key: 14,
          label: '标记',
          width: '80',
          prop: 'tag',
          visible: true
        },
        {
          key: 15,
          label: '备注',
          width: '120',
          prop: 'remark',
          visible: true
        },
        {
          key: 16,
          label: '发货仓库',
          width: '100',
          prop: 'warehouseName',
          sortable: 'custom',
          visible: true
        },
        {
          key: 17,
          label: '收货人',
          width: '100',
          prop: 'userName',
          visible: true
        },
        {
          key: 18,
          label: '收货人手机号',
          width: '110',
          prop: 'userMobile',
          visible: true
        },
        {
          key: 19,
          label: '收货地址',
          width: '180',
          prop: 'userAddress',
          visible: true
        },
      ],
      // 查询参数
      queryParams: {
        "brandCode": [],
        "categoryCode": [],
        "orderNos": [],
        "page": 1,
        "pageSize": 10,
        "payEndTime": "",
        "payStarTime": "",
        "platformNo": [],
        "shopCode": [],
        "skuNo": "",
        "skuNos": [],
        "warehouseCode": [],
        dateRange:[],
        tags: ['0']
      },
      brandNameList: [],
      detailRow: {},
      channelList: [],
      tableHeight: "auto",
      warehouseLists: [],
      categoryList: [],
      hasDesc: '',
      statusList: [
        { code: 0, name: "待提交" },
        { code: 1, name: "待审批" },
        { code: 2, name: "审批打回" },
        { code: 3, name: "启用" },
        { code: 4, name: "下线" },
        { code: 5, name: "挂起" },
        { code: 6, name: "变更待审批" },
        { code: 7, name: "变更审批打回" },
        { code: 8, name: "变更待提交" },
      ],
      randomKey: Math.random(),
      sorts: [],
      contextmenuShow: false,
      copyTextContent: [],
      columnIndex: [],
      rowIndex: [],
      pickerOptions: {
        shortcuts: [
          {
            text: "最近三天",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() - 3600 * 1000 * 24 * 3);
              picker.$emit("pick", [end, start]);
             
            },
          },
          {
            text: "最近一周",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() - 3600 * 1000 * 24 * 7);
               picker.$emit("pick", [end, start]);
            },
          },
          {
            text: "最近半个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() - 3600 * 1000 * 24 * 15);
               picker.$emit("pick", [end, start]);
            },
          },
          {
            text: "最近一个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() - 3600 * 1000 * 24 * 30);
               picker.$emit("pick", [end, start]);
            },
          },
          {
            text: "最近三个月",
            onClick(picker) {
              const end = new Date();
              const start = new Date();
              end.setTime(start.getTime() - 3600 * 1000 * 24 * 90);
               picker.$emit("pick", [end, start]);
            },
          },
        ],
      },
    };
  },
  created() {
    // if (localStorage.getItem("osOrder-query")) {
    //   this.queryParams = JSON.parse(localStorage.getItem("osOrder-query"));
    //   this.queryParams.page = 1;
    //   this.queryParams.pageSize = 10;
    // }

    const date = new Date();
    const year = date.getFullYear();
    const month =
      date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    const day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    const endDate = year + "-" + month + "-" + day;
    date.setTime(date.getTime() - 3600 * 1000 * 24 * 7);
    const year2 = date.getFullYear();
    const month2 =
      date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
    const day2 = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    const startDate = year2 + "-" + month2 + "-" + day2;
    this.queryParams.dateRange = [startDate, endDate];

    this.getList();
    this.getBrandNameList();
  },
  mounted() {
    const table = this.$refs.proTable2.$el;
    console.log(table)
    if(table){
      table.addEventListener('contextmenu', this.contextmenu);
    }
  },
  beforeDestroy() {
    const table = this.$refs.proTable2.$el;
    if(table){
      table.removeEventListener('contextmenu', this.contextmenu);
    }
  },
  methods: {
    contextmenu(e){
      e.preventDefault();
      if (
        e.target.offsetParent._prevClass.split(' ').indexOf('bg-r') != -1 ||
        e.target._prevClass.split(' ').indexOf('bg-r') != -1
      ) {
        this.openMenu(e);
      }
    },
    openMenu(e) {
      // console.log(e.pageY);
      // console.log(e.pageX);
      this.contextmenuShow = true;
      const scrollElem = this.$refs.chartBox;
      scrollElem.style.top = `${e.pageY}px`;
      scrollElem.style.left = `${e.pageX}px`;
    },
    closeCopy(){
      this.contextmenuShow = false;
    },
    cellClick(row, column, cell, event) {
      console.log(column)
      const columnIndex = column.index;

      if(this.columnIndex.indexOf(columnIndex)>-1){
        this.columnIndex.splice(this.columnIndex.indexOf(columnIndex),1)
      }else{
        this.columnIndex.push(columnIndex)
      }
      // const rowIndex = row.index;
      // let dx = null;
      // for(let i=0;i<this.columnIndex.length;i++){
      //   if(this.columnIndex[i].columnIndex==columnIndex&&this.columnIndex[i].rowIndex==rowIndex){
      //     dx = i;
      //     break;
      //   }
      // }
      // if(dx!=null){
      //   this.columnIndex.splice(dx, 1);
      // }else{
      //   this.columnIndex.push({
      //     columnIndex,
      //     rowIndex
      //   })
      // }
    },
    cellClassName({ row,column,rowIndex,columnIndex }) {
      // for(let i=0;i<this.columnIndex.length;i++){
      //   if(this.columnIndex[i].columnIndex==item.columnIndex&&this.columnIndex[i].rowIndex==item.rowIndex){
      //     return 'bg-r';
      //   }
      // }
      row.index = rowIndex;
      column.index = columnIndex;
      if (this.columnIndex.includes(columnIndex)) {
        // console.log(item)
        return 'bg-r';
      }
    },
    rowClassName({row,rowIndex}){
      return row.index = rowIndex;
    },
    copyText2(){
      this.copyTextContent = [];
      const list=document.querySelectorAll('.bg-r');
      list.forEach(item=>{
        if(!!item.innerText){
          this.copyTextContent.push(item.innerText)
        }
      })
      window.navigator.clipboard
        .writeText(this.copyTextContent.join('\n'))
        .then(() => {
          // this.$message.success("复制成功");
          this.contextmenuShow = false;
          this.$message({
            message: '复制成功',
            type: 'success',
            customClass: 'phone-message',
            center: true,
          });
        })
        .catch((error) => {
          // this.$message.warning("复制失败");
          this.$message({
            message: '复制失败',
            type: 'warning',
            customClass: 'phone-message',
            center: true,
          });
        });
    },
    copySkus(value,row){
        this.$set(this.queryParams,row,value.trim().split(/\s+/).join(','))
    },
    selectable(row){
      return row.tag==0;
    },
    getBrandNameList() {
      getBrandNameList().then((res) => {
        this.brandNameList = res.data;
        // if (localStorage.getItem("osOrder-query")) {
        //   this.brandChange(this.queryParams.brandCodes);
        // }
      });
      warehouseList().then((res) => {
        this.warehouseLists = res.data.list;
      });
      platformList().then(res=>{
        if(res.status==200){
          this.platformLists = res.data.platformListResDTOS;
        }
      });
      saleTargetChannelList().then((res) => {
        if(res.status==200){
          this.channelList = res.data || [];
        }
      });
      getCategory().then((res) => {
        if(res.status==200){
          this.categoryList = res.data || [];
        }
      });
    },
    brandChange(value) {
      // if (value.length != 0) {
      //   getSpuList(value).then((res) => {
      //     this.spuList = res.data;
      //   });
      // } else {
      //   this.spuList = [];
      // }
    },
    goJl(){
      sessionStorage.setItem('Jldetail-ids',JSON.stringify(this.ids));
      this.$router.push('/Jldetail');
    },
    /** 查询岗位列表 */
    getList() {
      if(this.queryParams.orderNos2){
        this.queryParams.orderNos = this.queryParams.orderNos2.split(',');
      }else{
        this.queryParams.orderNos = []
      }
      if(this.queryParams.skuNos2){
        this.queryParams.skuNos = this.queryParams.skuNos2.split(',');
      }else{
        this.queryParams.skuNos = []
      }
      if(this.queryParams.dateRange&&this.queryParams.dateRange.length>0){
        this.queryParams.payStarTime = this.queryParams.dateRange[0];
        this.queryParams.payEndTime = this.queryParams.dateRange[1];
      }

      localStorage.setItem("osOrder-query", JSON.stringify(this.queryParams));
      const data = {...this.queryParams};
      data.sorts = this.sorts;
      data.hasDesc = this.hasDesc;

      this.columnIndex = [];
      this.loading = true;
      shortageGood(data).then((response) => {
        this.postList = response.data.list;
        this.total = response.data.total;
        this.loading = false;

        this.$nextTick(() => {
          const height = window.innerHeight - this.$refs.queryForm.$el.offsetHeight - 210;
          console.log(height);
          this.tableHeight = height + "px";
        });
      });
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1;
      this.$refs.proTable2.clearSelection();
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.queryParams = {
        "brandCode": [],
        "categoryCode": [],
        "orderNos": [],
        "page": 1,
        "pageSize": 10,
        "payEndTime": "",
        "payStarTime": "",
        "platformNo": [],
        "shopCode": [],
        "skuNo": "",
        "skuNos": [],
        "warehouseCode": [],
        dateRange:[],
        tags: ['0']
      }
      const date = new Date();
      const year = date.getFullYear();
      const month =
        date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
      const day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      const endDate = year + "-" + month + "-" + day;
      date.setTime(date.getTime() - 3600 * 1000 * 24 * 30);
      const year2 = date.getFullYear();
      const month2 =
        date.getMonth() + 1 < 10 ? "0" + (date.getMonth() + 1) : date.getMonth() + 1;
      const day2 = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
      const startDate = year2 + "-" + month2 + "-" + day2;
      this.queryParams.dateRange = [startDate, endDate];


      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map((item) => {
        return {
          orderId: item.orderId,
          skuNo: item.goodCode
        }
      });
    },
    sortChange({ column, prop, order }){
      console.log(order)
      if(order){
        this.sorts = [];
        this.sorts.push(prop);
        if(order=='ascending'){
          this.hasDesc = 1;
        }else if(order=='descending'){
          this.hasDesc = 0;
        }
      }else{
        this.sorts = [];
      }
      this.getList();
    },
    updateG(row,type){
      shortageGoodUpdate({
        id: row.id,
        fieldName: 'tag',
        fieldValue: type
      }).then(res=>{
        if(res.status==200){
          this.$message.success('更新成功');
          this.getList()
        }
      })
    },
    showRemark(row){
      this.resetForm('remarkForm');
      this.detailRow = row;
      this.form.remark = row.remark || '';
      this.open = true;
    },
    submitForm(){
      this.$refs.remarkForm.validate((valid) => {
        if(valid){
          shortageGoodUpdate({
            id: this.detailRow.id,
            fieldName: 'remark',
            fieldValue: this.form.remark
          }).then(res=>{
            if(res.status==200){
              this.$message.success('修改成功');
              this.open = false;
              this.getList();
            }
          })
        }
      })
    },
    sortCol(value){
      value.forEach(item=>{
        if(item.fixc){
          item.fixed = 'left';
        }else{
          item.fixed = '';
        }
      })
      this.columns = value;
      this.randomKey = Math.random();
    },
  },
};
</script>
<style scoped>
.charts-box {
  height: 350px;
  margin-top: 30px;
}
.erpPrice > span {
  color: #409eff;
}
.iconEdit {
  cursor: pointer;
}
.app-container {
  padding-bottom: 50px;
}

.detail-btn {
  margin-left: 8px;
}
.chart-box {
  width: 150px;
  background-color: rgb(234, 237, 246);
  padding: 8px;
  position: fixed;
  left: 0;
  top: 0;
  z-index: 1000;
}
.chart-content {
  cursor: pointer;
}
.chart-content:hover {
  background-color: rgb(241 245 249);
  .copy-box {
    display: flex;
  }
}
::v-deep .bg-r {
  background-color: rgb(242, 251, 238)!important;
}
</style>
