<template>
  <div>
    <basic-container v-show="show" class="page-crad">
      <avue-crud
          :key="key"
          ref="crud"
          :option="option"
          :data="dataList"
          :page.sync="page"
          :search.sync="search"
          @search-change="searchChange"
          @current-change="currentChange"
          @size-change="sizeChange"
          @refresh-change="refreshChange"
          @on-load="onLoad"
          :table-loading="loading"
          @saveColumn="saveColumn"
          @resetColumn="resetColumn"
          :cell-style="cellStyle"
          @search-criteria-switch="searchCriteriaSwitch"
          @expand-change="expandChange">
        <template slot="menuLeft">
          <div style="display:flex;padding-top: 10px">
            <el-badge
                v-for="item of badgeList"
                :hidden="item.dictionaryStatus == '全部'?true:false"
                :value="item.count"
                :max="99"
                class="item"
                type="danger">
              <el-button
                  style="border-radius: 0"
                  :type="search.status == item.status?'success':''"
                  size="mini"
                  @click="query(item.status)">
                {{ item.dictionaryStatus }}
              </el-button>
            </el-badge>
            <el-button type="primary" size="mini" @click.stop="newAdd()">新建销售单</el-button>
          </div>
        </template>
        <template slot="expand" slot-scope="{row}">
          <avue-crud
              ref="expandCrud"
              :option="optionList"
              :table-loading="row.loading"
              :data="row.orderItemsList"></avue-crud>
        </template>
        <template slot="corpIdSearch">
          <crop-select v-model="search.corpId" corpType="KH"></crop-select>
        </template>
        <template slot-scope="{ row, index }" slot="corpId">
          <span style="color: #409EFF;cursor: pointer" @click.stop="editOpen(row, 1)">{{ row.corpsName }}</span>
        </template>
        <template slot-scope="{ row, index }" slot="sysNo">
          <span style="color: #409EFF;cursor: pointer" @click.stop="editOpen(row, 1)">{{ row.sysNo }}</span>
        </template>
        <template slot="businesDateSearch">
          <el-date-picker
              v-model="search.businesDate"
              type="daterange"
              start-placeholder="开始日期"
              end-placeholder="结束日期"
              format="yyyy-MM-dd"
              value-format="yyyy-MM-dd HH:mm:ss"
              :default-time="['00:00:00', '23:59:59']"
              :picker-options="pickerOptions">
          </el-date-picker>
        </template>
        <template slot-scope="{ row, index }" slot="menu">
          <!-- <el-tooltip class="item" effect="dark" content="新建销售订单" placement="top">
            <i class="tradingIcon icon-add" />
          </el-tooltip> -->
          <el-tooltip class="item" effect="dark" content="删除" placement="top">
            <i class="tradingIcon icon-del" v-if="row.confirmStatus == 0" @click.stop="rowDel(row, index)"/>
          </el-tooltip>
          <!--          <el-tooltip class="item" effect="dark" content="编辑" placement="top">-->
          <!--            <i class="tradingIcon icon-edit" />-->
          <!--          </el-tooltip>-->
          <!--          <el-tooltip class="item" effect="dark" content="收款" placement="top">-->
          <!--            <i class="tradingIcon icon-proceeds" />-->
          <!--          </el-tooltip>-->
          <el-tooltip class="item" effect="dark" content="发货" placement="top">
            <i class="tradingIcon icon-deliver" v-if="row.status == 3" @click.stop="deliverGoods(row, index)"/>
          </el-tooltip>
          <!--          <el-tooltip class="item" effect="dark" content="对账" placement="top">-->
          <!--            <i class="tradingIcon icon-reconciliation" />-->
          <!--          </el-tooltip>-->
          <!-- <el-button type="text" size="small" @click.stop="editOpen(row, 2)">
            查看
          </el-button>
          <el-button type="text" size="small" @click.stop="rowDel(row, index)">
            删除
          </el-button> -->
        </template>
      </avue-crud>
    </basic-container>
    <details-page v-if="!show" @goBack="goBack()" :detailData="detailData"/>
    <el-dialog
        title="发货"
        :visible.sync="dialogVisible"
        append-to-body
        close-on-click-modal
        close-on-press-escape
        width="40%">
      <div class="elForm">
        <el-form :model="form" label-position="right">
          <el-col :span="24">
            <el-form-item label="收货人姓名:" label-width="100px">
              <span>{{ form.corpAttn }}</span>
            </el-form-item>
            <el-form-item label="收货人电话:" label-width="100px">
              <span>{{ form.corpTel }}</span>
            </el-form-item>
            <el-form-item label="收货人地址:" label-width="100px">
              <span>{{ form.arrivalAddress }}</span>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="快递公司:" label-width="100px">
              <!--              <el-input v-model="form.courierCorporation" placeholder="请输入快递公司" size="small" style="width: 100%;"></el-input>-->
              <el-select v-model="form.courierCorporation" placeholder="请选择快递公司" clearable filterable
                         size="small" style="width: 90%;">
                <el-option
                    v-for="item in courierServices"
                    :key="item.dictKey"
                    :label="item.dictValue"
                    :value="item.dictKey">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="24">
            <el-form-item label="快递单号:" label-width="100px">
              <el-input
                  v-model="form.courierNumber"
                  placeholder="请输入快递单号"
                  size="small"
                  style="width: 90%;"></el-input>
            </el-form-item>
          </el-col>
        </el-form>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button size="small" @click="dialogVisible = false">取 消</el-button>
        <el-button size="small" type="primary" @click="confirmShipment">确认发货</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import detailsPage from "./detailsPage";
import {option} from "./js/optionList";
import {optionList} from "./js/optionList";
import {
  getListTwo,
  getCorpsAll,
  gainUser,
  getCorpType,
  orderRemove,
  statusStatisticsApi,
  delivery, getDetails, getStoragelist
} from "@/api/basicData/salesOrder";

export default {
  name: "index",
  data() {
    return {
      src: '',
      form: {},
      optionList: {
        header: false,
        align: "center",
        addBtn: false,
        refreshBtn: false,
        editBtn: false,
        delBtn: false,
        columnBtn: false,
        border: true,
        menuWidth: 120,
        stripe: true,
        index: true,
        menu: false,
        expandRowKeys: [],
        rowKey: 'id',
        indexSlot: true,
        showSummary: true,
        summaryText: "合计",
        sumColumnList: [
          {
            name: "amount",
            type: "sum"
          },
          {
            name: "storageAmount",
            type: "sum"
          },
          {
            name: "storageInQuantity",
            type: "sum"
          },
          {
            name: "actualQuantity",
            type: "sum"
          }
        ],
        column: [
          {
            label: "产品",
            prop: "cname",
            width: '250px',
            // overHidden: true
          },
          {
            label: "仓库",
            prop: "storageId",
            overHidden: true,
            type: "select",
            props: {
              label: "cname",
              value: "id"
            },
            dicData: []
          },
          {
            label: "数量",
            prop: "storageInQuantity",
            overHidden: true
          },
          {
            label: "单位",
            prop: "unit",
            type: "select",
            props: {
              label: "dictValue",
              value: "dictValue"
            },
            dicData: [],
            cell: true,
            overHidden: true
          },
          {
            label: "单价",
            prop: "price",
            overHidden: true
          },
          {
            label: "金额",
            prop: "amount",
            overHidden: true
          },
          {
            label: "送货数量",
            prop: "actualQuantity",
            type: 'number',
            controls: false,
            cell: true,
            overHidden: true
          },
          {
            label: "备注",
            prop: "remarks",
            cell: true,
            overHidden: true
          },
          {
            label: "进价",
            prop: "purchasePrice",
            overHidden: true
          }
        ]
      },
      dialogVisible: false,
      badgeList: [],
      show: true,
      loading: false,
      search: {
        status: ''
      },
      detailData: {},
      dataList: [],
      selectionList: [],
      key: 0,
      page: {
        pageSize: 20,
        currentPage: 1,
        total: 0,
        pageSizes: [10, 20, 30, 40, 50, 100, 200, 300, 400, 500]
      },
      option: {},
      pickerOptions: {
        shortcuts: [
          {
            text: '当天',
            onClick(picker) {
              const date = new Date();
              const start = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 0, 0, 0);
              const end = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59);
              picker.$emit('pick', [start, end]);
            }
          },
          {
            text: '昨天',
            onClick(picker) {
              const date = new Date();
              const start = new Date(date.getFullYear(), date.getMonth(), date.getDate() - 1, 0, 0, 0);
              const end = new Date(date.getFullYear(), date.getMonth(), date.getDate() - 1, 23, 59, 59);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '当月',
            onClick(picker) {
              const date = new Date();
              const start = new Date(date.getFullYear(), date.getMonth(), 1, 0, 0, 0);
              const end = new Date(date.getFullYear(), date.getMonth() + 1, 0, 23, 59, 59);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '当季',
            onClick(picker) {
              const date = new Date();
              const start = new Date(date.getFullYear(), parseInt(date.getMonth() / 3) * 3, 1, 0, 0, 0);
              const end = new Date(date.getFullYear(), parseInt(date.getMonth() / 3) * 3 + 3, 0, 23, 59, 59);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '当年',
            onClick(picker) {
              const date = new Date();
              const start = new Date(date.getFullYear(), date.getMonth(), 1, 0, 0, 0);
              const end = new Date(date.getFullYear() + 1, 0, 0, 23, 59, 59);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近一周',
            onClick(picker) {
              const date = new Date();
              const start = new Date(date.getFullYear(), date.getMonth(), date.getDate() - 7, 0, 0, 0);
              const end = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近二周',
            onClick(picker) {
              const date = new Date();
              const start = new Date(date.getFullYear(), date.getMonth(), date.getDate() - 7 * 2, 0, 0, 0);
              const end = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59);
              picker.$emit('pick', [start, end]);
            }
          }, {
            text: '最近三周',
            onClick(picker) {
              const date = new Date();
              const start = new Date(date.getFullYear(), date.getMonth(), date.getDate() - 7 * 3, 0, 0, 0);
              const end = new Date(date.getFullYear(), date.getMonth(), date.getDate(), 23, 59, 59);
              picker.$emit('pick', [start, end]);
            }
          }]
      },
      courierServices: []
    };
  },
  components: {
    detailsPage
  },
  async created() {
    this.option = await this.getColumnData(this.getColumnName(211), option);
    this.getAllWorkDicts()
    this.getWorkDicts("order_status_pjjl").then(res => {
      this.findObject(this.option.column, "status").dicData = res.data.data;
      this.findObject(this.option.column, "actualPaymentStatus").dicData = res.data.data;
      this.key++
    });
    this.getWorkDicts("courier_services").then(res => {
      this.courierServices = res.data.data
    });
  },
  activated() {
    this.$refs.crud.refreshTable();
    if (!this.$store.getters.pjxsStatus && !this.show) {
      this.show = true;
    }
    if (this.$route.query.orderId) {
      setTimeout(() => {
        this.editOpen({id: this.$route.query.orderId}, 1);
      }, 100);
    }
    if (this.$route.query.check) {
      this.show = true
      this.detailData = {
        id: this.$route.query.check.billId,
        check: this.$route.query.check,
        auditId: this.$route.query.check.id,
      };
      this.show = false;
      this.$store.commit("IN_PJXS_STATUS");
    }
  },
  methods: {
    confirmShipment() {
      if (!this.form.courierNumber) {
        this.$alert('是否继续发货', '未填写快递单号', {
          confirmButtonText: '确定',
          callback: action => {
            if (action === "confirm") {
              const loading = this.$loading({
                lock: true,
                text: '加载中',
                spinner: 'el-icon-loading',
                background: 'rgba(255,255,255,0.7)'
              });
              delivery({
                id: this.form.id,
                courierNumber: this.form.courierNumber,
                courierCorporation: this.form.courierCorporation
              }).then(res => {
                loading.close();
                this.$message.success("发货成功")
                this.dialogVisible = false
                this.onLoad(this.page)
              }).catch(() => {
                loading.close();
              })
            }
          }
        });
      } else {
        const loading = this.$loading({
          lock: true,
          text: '加载中',
          spinner: 'el-icon-loading',
          background: 'rgba(255,255,255,0.7)'
        });
        delivery({
          id: this.form.id,
          courierNumber: this.form.courierNumber,
          courierCorporation: this.form.courierCorporation
        }).then(res => {
          this.$message.success("发货成功")
          this.dialogVisible = false
          loading.close();
          this.onLoad(this.page)
        }).catch(() => {
          loading.close();
        })
      }
    },
    query(status) {
      this.search.status = status
      this.page.currentPage = 1;
      this.onLoad(this.page)
    },
    getAllWorkDicts() {
      gainUser().then(res => {
        this.findObject(this.option.column, "createUser").dicData = res.data.data;
      })
      getCorpType({corpType: 'KH'}).then(res => {
        this.findObject(this.option.column, "corpType").dicData = res.data.data;
      });
      this.$refs.crud.init();
    },
    expandChange(row, expendList) {
      this.getWorkDicts("unit").then(res => {
        this.findObject(this.optionList.column, "unit").dicData = res.data.data;
      });
      getStoragelist().then(res => {
        this.storageoptions = res.data;
        this.findObject(this.optionList.column, "storageId").dicData = res.data;
      })
      if (row) {
        row.loading = true
        getDetails({id: row.id}).then(res => {
          row.orderItemsList = res.data.data.orderItemsList
          row.loading = false
        })
      }
    },
    searchCriteriaSwitch(type) {
      this.$refs.crud.getTableHeight();
    },
    cellStyle() {
      return "padding:0;height:40px;";
    },
    //点击搜索按钮触发
    searchChange(params, done) {
      this.page.currentPage = 1;
      this.onLoad(this.page, params);
      done();
    },
    refreshChange() {
      this.onLoad(this.page, this.search);
    },
    newAdd() {
      this.show = false;
      this.$store.commit("IN_PJXS_STATUS");
    },
    onLoad(page, params = {}) {
      if (this.$refs.expandCrud) {
        this.dataList.forEach(item => {
          this.$refs.crud.toggleRowExpansion(item, false);
        });
      }
      statusStatisticsApi({type: '1'}).then(res => {
        this.badgeList = [];
        this.badgeList.push({
          count: 0,
          dictionaryStatus: "全部",
          status: ''
        });
        for (let item of res.data.data) {
          this.badgeList.push(item)
        }
      })
      let data = this.deepClone(Object.assign(params, this.search));
      data.billType = 'XS';
      data.tradeType = 'YPJ';
      if (data.businesDate) {
        data.orderStartDate = data.businesDate[0];
        data.orderEndDate = data.businesDate[1];
      }
      delete data.businesDate
      this.loading = true;
      getListTwo(
        page.currentPage,
        page.pageSize,
        data
      ).then(res => {
        this.dataList = res.data.data.records ? res.data.data.records : [];
        this.page.total = res.data.data.total;
      }).finally(() => {
        this.loading = false;
      });
    },
    editOpen(row, status) {
      this.detailData = {
        id: row.id,
        status: status,
        billType: row.billType
      };
      this.show = false;
      this.$store.commit("IN_PJXS_STATUS");
    },
    currentChange(val) {
      this.page.currentPage = val;
    },
    sizeChange(val) {
      this.page.currentPage = 1;
      this.page.pageSize = val;
    },
    rowDel(row, index, done) {
      this.$confirm("确定删除数据?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        orderRemove(row.id).then(res => {
          if (res.data.code == 200) {
            this.$message({
              type: "success",
              message: "删除成功!"
            });
            this.onLoad(this.page, this.search);
          }
        });
      });
    },
    deliverGoods(row, index) {
      this.form = row
      this.dialogVisible = true
    },
    async saveColumn() {
      const inSave = await this.saveColumnData(
        this.getColumnName(211),
        this.option
      );
      if (inSave) {
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
        });
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs.crud.$refs.dialogColumn.columnBox = false;
      }
    },
    async resetColumn() {
      this.option = option;
      const inSave = await this.delColumnData(this.getColumnName(211), option);
      if (inSave) {
        this.$nextTick(() => {
          this.$refs.crud.doLayout();
        });
        this.getAllWorkDicts()
        this.$message.success("重置成功");
        this.$refs.crud.$refs.dialogColumn.columnBox = false;
      }
    },
    //返回列表
    goBack() {
      if (this.$route.query.orderId || this.$route.query.check) {
        this.$router.$avueRouter.closeTag(this.$route.fullPath);
        this.$router.push({
          path: "/salesOrder/index"
        });
      }
      this.detailData = this.$options.data().detailData;
      this.show = true;
      this.onLoad(this.page, this.search);
      this.$store.commit("OUT_PJXS_STATUS");
    },
  }
}
</script>

<style lang="scss" scoped>
.page-crad ::v-deep .basic-container__card {
  height: 94.2vh;
}

::v-deep .el-badge__content.is-fixed {
  z-index: 10;
  right: 25px
}

.item {
  margin-right: -5px;
  //margin-bottom: 10px;
}

.stat-td {
  text-align: center;
  position: relative;
}

.stat-img {
  width: 95%;
  height: 100px;
}

.stat-tip {
  position: absolute;
  left: 15px;
  top: 5px;

  .money {
    color: #fff;
    font-size: 28px;
    text-align: left;
    font-weight: 600;
  }

  .title {
    color: #fff;
    font-size: 14px;
    text-align: left;
    margin-top: 5px;
    margin-bottom: 0px;
  }
}

::v-deep .el-form-item__content {
  //margin-left: 90px;
}

::v-deep .avue-crud__right {
  padding-top: 5px;
}

::v-deep .elForm {
  .el-form-item {
    margin-bottom: 0;
  }
}

::v-deep .el-dialog__body {
  padding: 0;
}

::v-deep .el-form-item__label {
  //text-align: right;
  //vertical-align: middle;
  //float: left;
  //font-size: 14px;
  //color: #606266;
  //line-height: 40px;
  padding: 0 4px 0 0;
  //box-sizing: border-box;
}
</style>
