<template>
  <div class="app-container">
    <div class="app-container__title">{{title}}</div>
    <el-card class="app-container__search">
      <xd-search
        main-filter-key="main_key"
        :main-filter="null"
        :main-filter-index="4"
        :main-filter-stretch="false"
        main-filter-type=""
        :mainFilter="tabData"
        v-if="searchForm.length > 0"
        :list="searchForm"
        dateFilter
        labelWidth="100px"
        :time-type="true"
        v-model="searchParams"
        @onSearch="handleSearch"
        @onDone="getList"
      >
        <template slot="shop_name">
          <xd-select-list
            is-remote
            placeholder="请输入店铺名称"
            v-model="shopId"
            :key="shop_id_key"
            @change="handleSelect"
            @onSearch="handleSearchShop"
          ></xd-select-list>
        </template>
        <template slot="brand_name">
          <xd-select-list
            is-remote
            placeholder="请输入品牌名称"
            v-model="brand_id"
            :key="brand_id_key"
            @onSearch="handleSearchBrand"
          ></xd-select-list>
        </template>
      </xd-search>
    </el-card>
    <el-card class="app-container__list">
      <div class="app-container__list-pagination">
        <div>
          <el-button
            size="medium"
            type="primary"
            @click="batchShipment"
          >批量发货
          </el-button>
        </div>
      </div>
      <div class="app-container__list-table">
        <xd-table
          :default-select="['12987122','12987126']"
          :get-link="getLink"
          :headers="orderHeaders"
          :list="list2"
          :hasExpand="true"
          :stripe="false"
          :custom-function="handleCustom"
          default-expand-all
          @onClick="handleCilck"
          @onSelect="handleSelect"
        >
          <template slot="expand" slot-scope="scope">
            <xd-table
              is-border
              :stripe="false"
              :show-header="false"
              :get-link="getLinkChild"
              :headers="orderHeadersIn"
              :list="list3"
              :custom-function="handleInCustom"
              default-expand-all
              @onClick="handleCilck"
              @onSelect="handleSelect"
            >
              <template slot="status">
                {{scope.row.status}}
              </template>
              <template slot="total">
                <xd-table-price
                  :price="scope.row.total"
                ></xd-table-price>
              </template>
            </xd-table>
          </template>
          <template slot="info" slot-scope="scope">
            <div class="order-table-info" v-html="getInfo(scope.row)"></div>
          </template>
        </xd-table>
      </div>
      <div class="app-container__list-pagination">
        <xd-pagination
          :total="200"
          :limit.sync="limit"
          :page="pageSize"
          :auto-scroll="false"
          @onPagination="handlePagination"
        ></xd-pagination>
      </div>
    </el-card>
    <xd-dialog
      title="发货管理"
      v-if="dialogVisibleExpress"
      :show.sync="dialogVisibleExpress"
      width="50%"
      @onConfirm="handleUploadEXpress"
      @onClose="handleCloseEXpress"
      @onCancel="handleCloseEXpress"
    >
      <el-form :model="experssForm" label-width="100px">
        <div class="app-container__list-table">
          <xd-table
            ref="saveTableRef"
            :headers="headersExperss"
            :list="tablesExperss"
            @change="saveTableChange"
            is-border
          >
          </xd-table>
        </div>
        <div style="margin-bottom:10px">
          <el-card>
            <xd-detail
              label-width="100"
              :is-border="isBorder"
              :list="subBaseData"
              size=""
            >
            </xd-detail>
          </el-card>
        </div>
        <el-form-item label="快递信息">
          <xd-add-express
            v-model="xdAddExpressValue"
            :express="expressList"
            :defaultValue="expressDatas"
            btn-name="提交"
            width="450px"
            :is-submit="false"
            :isComment="false"
          ></xd-add-express>
        </el-form-item>
      </el-form>
    </xd-dialog>
  </div>

</template>

<script>
  import XdSearch from "@/components/XdSearch";
  import XdPaginationCustom from "@/components/XdPaginationCustom";
  import XdTableStatus from "@/components/XdTableStatus";
  import XdTableImage from "@/components/XdTableImage";
  import XdSelectList from "@/components/XdSelectList";
  import {baseJsDateToTime} from '@/utils/xd.base'
  import {getCurrentToken} from '@/utils/auth'
  import checkPermission from "@/utils/permission";
  import roles from '@/constant/permissions';
  import urls from '@/apiurl/index'
  import {mapActions} from 'vuex';
  import {Loading} from 'element-ui';
  // import downloadString from "@/mixins/downloadString";
  // import getChannelList from "@/mixins/getChannelList";
  import XdDialog from "@/components/XdDialog";
  import XdAddExpress from "./compontents/expressCopy";
  import XdPagination from "@/components/XdPagination.vue";
  import XdTable from "@/components/XdTable";
  import XdTablePrice from "@/components/XdTablePrice";
  import XdDetail from "@/components/XdDetail";

  export default {
    name: "cake_order",
    components: {
      XdPagination,
      XdSearch,
      XdTableStatus,
      XdTableImage,
      XdSelectList,
      XdDialog,
      XdAddExpress,
      XdTable,
      XdTablePrice,
      XdDetail
    },

    // mixins: [downloadString, getChannelList],

    data() {
      return {
        pageSize: 1,//当前页面数量
        hasNextPage: true,
        limit: 20,

        searchForm: [], //搜索区域模块表单
        searchParams: null, // 搜索参数

        shopId: null,
        shop_id_key: 0,

        brand_id: null,
        brand_id_key: 0,
        companyId: null,
        tables: [],
        company_shop_origin: 1,
        multipleSelection: [],
        dialogVisibleExpress: false,
        expressList: null,
        orderNumber: "",
        subOrderNumber: '',
        experssForm: {},
        xdAddExpressValue: [],
        tabData: [
          {label: '全部', value: '1'},
          {label: '待付款', value: '2'},
          {label: '待发货', value: '3'},
          {label: '待收货', value: '4'},
          {label: '已完成', value: '5'},
          {label: '已关闭', value: '6'},
        ],
        headers: [
          {"type": "selection", "align": "center",},
          {"type": "normal", "prop": "order_id", "align": "center", "label": "订单ID"},
          {"type": "normal", "prop": "order_id", "align": "center", "label": "流水号"},
          {"type": "normal", "prop": "product_name", "align": "center", "label": "终端号"},
          {"type": "normal", "prop": "num", "align": "center", "label": "店铺名称"},
          {"type": "normal", "prop": "price", "align": "center", "label": "渠道ID"},
          {"type": "normal", "prop": "name", "align": "center", "label": "消费金额"},
          {"type": "normal", "prop": "phone", "align": "center", "label": "补差"},
          {"type": "normal", "prop": "status", "align": "center", "label": "结算标签"},
          {"type": "status", "prop": "status", "align": "center", "width": 100, "label": "订单状态"},
          {"type": "normal", "prop": "status", "align": "center", "label": "付款时间"},
          {"type": "normal", "prop": "status", "align": "center", "label": "退款时间"},
          {
            "type": "operate",
            "align": "center",
            "width": 170,
            "label": "操作",
            "values": [{"ui": "link", "icon": "el-icon-view", "target": "_blank", "name": "查看", "type": "primary"},]
          }],
        orderHeaders: [
          {type: 'selection'},
          {type: 'expand', hide: true},
          {type: 'normal', sort: true, prop: 'info', align: 'center', minWidth: 150, label: '商品信息'},
          {
            type: 'priceNumber',
            prop: 'priceNumber',
            align: 'center',
            width: 150,
            label: '价格&数量',
            message: ['price', 'number']
          },
          {type: 'normal', prop: 'status', align: 'center', width: 120, label: '订单状态'},
          {type: 'price', prop: 'total', align: 'center', width: 150, label: '实付款'},
          {
            type: 'operate',
            align: 'center',
            prop: 'operate',
            width: 110,
            label: '操作',
            values: [
              {ui: 'text-link', target: '_blank', name: '查看订单', type: 'text'},
            ]
          }
        ],
        orderHeadersIn: [
          {type: 'normal', sort: true, prop: 'info', align: 'left', minWidth: 150, label: '商品信息', rowspan: 4},
          {
            type: 'priceNumber',
            prop: "priceNumber",
            align: 'center',
            width: 150,
            label: '价格&数量',
            message: ['price', 'number']
          },
          {type: 'normal', prop: 'status', align: 'center', width: 120, label: '订单状态'},
          {type: 'price', prop: 'total', align: 'center', width: 150, label: '实付款'},
          {
            type: 'operate',
            align: 'center',
            prop: 'operate',
            width: 110,
            label: '操作',
            values: [
              {ui: 'text-button', target: '_blank', name: '发货', type: 'text'},
            ]
          }
        ],
        list: [],
        list2: [],
        list3: [],
        dialogVisibleExpress: false,
        headersExperss: [{"type": "selection"},
          {"type": "normal", "prop": "product", "align": "center", "width": 120, "label": "商品信息"},
          {"type": "normal", "prop": "number", "align": "center", "minWidth": 120, "label": "已换数量"},
          {
            type: 'priceNumber',
            prop: "priceNumber",
            align: 'center',
            width: 150,
            label: '价格&数量',
            message: ['price', 'number']
          },
          {"type": "normal", "prop": "t_price", "align": "center", "minWidth": 120, "label": "可退金额"},
          {"type": "input", "prop": "s_price", "align": "center", "minWidth": 120, "label": "退款金额"},
        ],
        tablesExperss: [
          {
            order_id: '12987122',
            info: '好滋好味鸡蛋仔',
            total: 8000,
            price: 8000,
            status: '待支付',
            number: '1',
            created: '2022-10-28 14:14:46',
            in: true,
            s_price: 1
          },
          {
            order_id: '12987123',
            info: '荷兰优质淡奶',
            total: 80000,
            price: 80000,
            status: '已完成',
            number: '1',
            created: '2022-10-28 14:14:46',
            in: true,
            s_price: 2
          },
        ],
        isBorder:false,
        subBaseData: [{
          title: '',
          items: [
            {
              label: '收货人',
              value: '123***123', type: 'normal',
              field: 'number',
              params: {
                handle: true,
                name: '查看用户信息',
                type: 'default'
              }
            },
            {
              label: '手机号',
              value: '186****1245', type: 'normal',
              field: 'iPhone',
              params: {
                handle: true,
                name: '查看联系电话',
                type: 'default'
              }
            },
            {label: '收货地址', value: '100', type: 'normal', field: 'address'},
            {label: '配送时间', value: '22', type: 'normal', field: 'time'},
            {label: '订单备注', value: '22', type: 'normal', field: 'remake'},
            {label: '祝福语', value: '22', type: 'normal', field: 'wish'},
          ],
        },],
      }
    },

    computed: {
      // showExport() {
      //   return checkPermission([roles.order.order.export])
      // },
      // showChannel() {
      //   return checkPermission([roles.order.order.channel])
      // },
    },

    created() {
      this.title = this.$route.meta.title;
      // this.getChannelSetting()
      //   .then(channel => {
      this.initSearchForm();
      //   })
      //   .catch()
      this.list2 = [
        {
          order_id: '12987122',
          info: '好滋好味鸡蛋仔1',
          total: 8000,
          price: 8000,
          status: '待支付',
          number: '1件',
          created: '2022-10-28 14:14:46',
        },
        {
          order_id: '12987123',
          info: '荷兰优质淡奶1',
          total: 80000,
          price: 80000,
          status: '已完成',
          number: '1件',
          created: '2022-10-28 14:14:46',
        },
        {
          order_id: '129871223',
          info: '荷兰优质淡奶1',
          total: 80000,
          price: 80000,
          status: '已完成',
          number: '1件',
          created: '2022-10-28 14:14:46',
        },
      ];
      this.list3 = [
        {
          order_id: '12987122',
          info: '好滋好味鸡蛋仔',
          total: 8000,
          price: 8000,
          status: '待支付',
          number: '1',
          created: '2022-10-28 14:14:46',
          in: true,
        },
        {
          order_id: '12987123',
          info: '荷兰优质淡奶',
          total: 80000,
          price: 80000,
          status: '已完成',
          number: '1',
          created: '2022-10-28 14:14:46',
          in: true,
        },
      ];
    },

    methods: {

      ...mapActions('order', ['getOrderList']),
      ...mapActions('product', [
        'getBrandList',
        'getShopList',
        'getCascaderList',
        'getAllShops'
      ]),

      getList() {
        this.tables = [
          {name: '张三', phone: '18666666666', order_id: '123456'}
        ];
        // let params = {
        //   ...this.searchParams,
        //   page: this.pageSize,
        //   shop_id: this.shopId ? this.shopId : null,
        //   brand_id: this.brand_id ? this.brand_id : null,
        //   company_shop_origin: this.company_shop_origin,
        //   limit: this.limit,
        // };
        // if (this.searchParams && this.searchParams['start_time'] && this.searchParams['end_time']) {
        //   params['created_time_range'] = [this.searchParams['start_time'], this.searchParams['end_time']]
        // }
        // let loading = Loading.service({});
        // this.getOrderList(params).then(res => {
        //   let data = res.list;
        //   console.log(data, 'datadata')
        //   data.map(item => {
        //     if (item.express_data && item.express_data.length > 0) {
        //       item.express_data.map(news => {
        //         news.company = news.express_id;
        //         news.number = news.express_number;
        //         news.express_name = news.express_name;
        //       })
        //     }
        //   })
        //   this.tables = data;
        //   this.hasNextPage = !(res.list && res.list.length < this.limit);
        //   loading.close();
        // }).catch(err => {
        //   console.log(err, 'aahhaha')
        //   loading.close();
        // })
      },

      orderExport() {
        let paramsStr = 'company_shop_origin=1&';

        paramsStr = this.setMapParamsStr(this.$xdHelper.cloneDeep(this.searchParams), paramsStr);

        if (this.shopId) {
          paramsStr += `shop_id=${this.shopId}&`
        }
        if (this.brand_id) {
          paramsStr += `brand_id=${this.brand_id}&`
        }

        paramsStr += `admin-cake-token=${getCurrentToken()}`

        let downloadUrl = `${this.$xdBrandInfo['api_host']}${urls.order.getOrderList}?is_download=1&${paramsStr}`
        console.warn(downloadUrl, '$xdBrandInfo$xdBrandInfo')
        window.open(downloadUrl)
      },

      /**
       * @description 初始化搜索模块
       */
      initSearchForm(channel) {
        let end = new Date().getTime();
        let start = end - 60 * 60 * 24 * 30 * 1000;

        let searchForm = [
          {
            label: '订单ID:', //label
            ele: 'el-input',
            valueKey: 'order_id', //form[valueKey]
            value: '', //v-model
            placeholder: '请输入订单ID'
          },
          {
            label: '订单支付单号:', //label
            ele: 'el-input',
            valueKey: 'order_number', //form[valueKey]
            value: '', //v-model
            placeholder: '请输入主单支付单号'
          },
          {
            label: '供应商:', //label
            ele: 'xd-select-list',
            valueKey: 'category_id', //form[valueKey]
            value: '', //v-model
            placeholder: '请选择供应商',
            multiple: false,
            width: '183px',
            list: []
          },
          {
            label: '票券号:', //label
            ele: 'el-input',
            valueKey: 'order_number', //form[valueKey]
            value: '', //v-model
            placeholder: '请输入票券号'
          },
          {
            label: '店铺名称:',
            ele: 'slot',
            slot: 'shop_name'
          },
          {
            label: '买家ID:', //label
            ele: 'el-input',
            valueKey: 'order_number', //form[valueKey]
            value: '', //v-model
            placeholder: '请输入买家ID'
          },
          {
            label: '订单类型:', //label
            ele: 'xd-select-list',
            valueKey: 'type', //form[valueKey]
            value: 0, //v-model
            placeholder: '请选择订单类型',
            multiple: false,
            width: '183px',
            list: [{value:0,label:'全部'}, {value: 1, label: '电子码'}, {value: 2, label: '实物'}, {value: 3, label: '虚拟'}]
          },
          {
            label: '收货人姓名:', //label
            ele: 'el-input',
            valueKey: 'order_number', //form[valueKey]
            value: '', //v-model
            placeholder: '请输入收货人姓名'
          },
          {
            label: '收货人手机号:', //label
            ele: 'el-input',
            valueKey: 'order_number', //form[valueKey]
            value: '', //v-model
            placeholder: '请输入收货人手机号'
          },
          //时间插件
          {
            label: '下单时间:', //label
            ele: 'xd-date', //package 名称
            valueKey: ['start_time', 'end_time'], //form[valueKey]
            value: [start, end], //v-model
            format: 'yyyy/MM/dd HH:mm:ss',//时间显示格式
            formatValue: 'timestamp', //输出时间格式
            placeholder: ['开始时间', '结束时间'],
          },
        ];
        this.searchForm = searchForm;

        // //设置是否可以可看
        // searchForm = searchForm.filter((item) => {
        //   if (item.valueKey === 'third_platform') {
        //     return !!this.showChannel;
        //   }
        //   return true;
        // });

        // Promise.all([
        //   this.getCascaderList({limit: 500}),
        //   this.getBrandList({page: 1, limit: 10})]).then(res => {
        //   searchForm.map((item, index, arr) => {
        //     switch (item.valueKey) {
        //       case 'category_id':
        //         let categoryList = res[0].list.map(item => {
        //           return {
        //             label: item.category_name,
        //             value: item.id
        //           }
        //         })
        //         item.list = categoryList
        //         break;
        //
        //       case 'brand_id':
        //         let brandList = res[1].list.map(item => {
        //           return {
        //             label: item.brand_name,
        //             value: item.id
        //           }
        //         })
        //         item.list = brandList
        //         break;
        //
        //     }
        //     arr.splice(index, 1, item)
        //   })
        //   this.searchForm = searchForm;
        //
        // }).catch(err => {
        //   console.log(err, 'err')
        // })


      },

      parseTime(time) {
        return baseJsDateToTime(time)
      },


      /**
       * @description 搜索事件
       * @param action 动作
       * @param form 搜索请求参数
       */
      handleSearch({action, form}) {
        this.pageSize = 1;
        this.hasNextPage = true;
        setTimeout(() => {
          if (action === 'reset') {
            this.shopId = null;
            this.brand_id = null;
            this.shop_id_key = this.$xdHelper.randomChar(20);
            this.brand_id_key = this.$xdHelper.randomChar(20);
          }
          this.$nextTick(() => {
            this.getList();
          });
        }, 100);
      },

      /**
       * @description 选中商铺
       */
      handleSelect({value, select}) {
        if (value !== this.shopId) {
          this.shopId = value;
          this.pageSize = 1;
        }
      },

      /**
       * @description 搜索商铺
       */
      handleSearchShop({query}, resolve) {
        if (!query) {
          resolve([]);
          return;
        }

        let params = {
          shop_name: query,
          limit: 1000,
          page: 1
        }

        //获取商铺列表
        this.getAllShops(params).then(res => {
          let shopList = [];
          if (res && res.list) {
            shopList = res.list.map(item => {
              return {
                label: item.shop_name,
                value: item.id
              }
            })
          }
          resolve(shopList)
        }).catch(err => {
          resolve([]);
        })
      },

      /**
       * @description 搜索品牌
       */
      handleSearchBrand({query}, resolve) {
        if (!query) {
          resolve([]);
          return;
        }

        let params = {
          brand_name: query,
          limit: 500,
          page: 1
        };

        this.getBrandList(params)
          .then(res => {
            console.log('getBrandList', res)
            let brandList = [];
            if (res && res.list) {
              brandList = res.list.map(item => {
                return {
                  label: `【${item.id}】${item.brand_name}`,
                  value: item.id
                }
              });
            }
            resolve(brandList)
          })
          .catch(res => {
            resolve([]);
          })
      },


      handlePagination(page) {
        this.pageSize = page;
        this.getList()
      },

      handleCompleted() {
        this.getList();
      },
      /**批量发货**/
      orderSend() {
        this.dialogVisibleExpress = true;
      },

      handleSelectionChange(value) {
        this.multipleSelection = value;
      },

      handleClose() {
        console.log('handleClose')
        this.expressName = '';
        this.expressNumber = '';
        this.expressId = '';
        this.dialogVisibleExpress = false;
      },

      getLink({row, value, index}) {
        return `/corders/detail/${row.order_id}`;
      },

      handleCustom({action, data}) {
        if (action === 'merge') {
          //这里必须启用懂下来列才能使用下来功能
          //合并列操作 从第3列开始一共合并5列，被合并列必须返回[0,0]
          let mergeColumn = 4;
          let startColumn = 2;

          //rowIndex，columnIndex的值是从0开始
          let {row, column, rowIndex, columnIndex} = data;

          if (columnIndex === startColumn) {
            return [1, mergeColumn]
          }
          if (columnIndex > startColumn && columnIndex < startColumn + mergeColumn) {
            return [0, 0]
          }
        }
      },

      handleInCustom({action, data}) {
        if (action === 'merge') {
          let mergeRow = 1;
          let maxRow = this.list2.length; //需要合并的最大行数
          let {row, column, rowIndex, columnIndex} = data;

          //rowIndex，columnIndex的值是从0开始
          let mergeColumns = [2, 3, 4, 5]; //第4列需要合并行，并且合并到数组最大值,

          const check = (i) => {
            return mergeColumns.filter(key => {
              return key === i
            }).length > 0
          }

          if (rowIndex === 0) {
            if (check(columnIndex)) {
              return [maxRow, 1]
            } else return [1, 1]
          } else {
            if (check(columnIndex)) {
              return [0, 0]
            } else return [1, 1]
          }

          //合并列操作 从第2列开始并合并5列，被合并列必须返回[0,0]
          // let mergeColumn = 2;
          // let startColumn = 4;
          // let {row, column, rowIndex, columnIndex} = data;
          // if (columnIndex === startColumn) {
          //   return [1, mergeColumn]
          // }
          // if (columnIndex > startColumn && columnIndex < startColumn + mergeColumn) {
          //   return [0, 0]
          // }
        }
      },


      getInfo(row) {
        return `订单号：${row.order_id}<span style="padding: 0 10px"></span>下单时间：${row.created}`
      },
      handleCilck({row, value, index}) {
        console.log('handleCilck', row, value, index)
        this.dialogVisibleExpress = true;
      },

      getLinkChild({row, value, index}) {
        return `/table/form/${row.id}`;
      },
      /**批量发货**/
      batchShipment(){
        this.dialogVisibleExpress = true;
      },
      /**发货确认**/
      handleUploadEXpress() {
        console.log(this.$refs.saveTableRef.getTableData(), this.xdAddExpressValue, 'expresss')
      },
      /**发货改变金额**/
      saveTableChange() {
        console.log(this.$refs.saveTableRef.getTableData(), 'eeee')
      },
      handleCloseEXpress(){
        this.dialogVisibleExpress = false;
      },

    }
  }
</script>

<style scoped lang="scss">
  .app-container__title {
    font-size: 16px;
    line-height: 24px;
    padding: 0 0 20px;
    font-weight: bold;
  }

  @media screen and (max-width: 768px) {
    .app-container__title {
      padding: 0 0 10px;
    }
  }
</style>
