<template>
  <zj-tab-page ref="tabPage" :defaultActives="[{ key: 'list', label: $route.meta.title + '-列表', essential: true }]">
    <template slot-scope="{ activeKey, data }">
      <template-page
        v-if="activeKey == 'list'"
        ref="pageRef"
        :get-list="getList"
        :table-attributes="tableAttributes"
        :table-events="tableEvents"
        :options-evens-group="optionsEvensGroup"
        :moreParameters="moreParameters"
        :column-parsing="columnParsing"
        :operation="operation()"
        :exportList="exportList"
      >
        <div slot="moreSearch">
          <el-radio-group v-model="examineStatus" size="mini" @change="changeType">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button label="SAVE">保存</el-radio-button>
            <el-radio-button label="SUBMIT">提交</el-radio-button>
            <el-radio-button label="WAIT">待审核</el-radio-button>
            <el-radio-button label="OK">审核通过</el-radio-button>
            <el-radio-button label="FAIL">审核驳回</el-radio-button>
          </el-radio-group>
          <br /><br />
        </div>
      </template-page>

      <div v-if="~['add', 'edit'].indexOf(activeKey)" style="box-sizing: border-box; padding: 16px">
        <el-form ref="formRef" :model="formData" :rules="formRules" label-position="left" label-width="90px">
          <div style="font-weight: 500">单据信息</div>
          <el-divider></el-divider>
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="发货单号" prop="deliveryId">
                <div style="display: flex; align-items: center">
                  <el-input v-model="formData.deliveryId" autocomplete="off" placeholder="请选择" disabled></el-input>
                  <el-button
                    type="primary"
                    size="small"
                    @click="openOrderDialog"
                    style="margin-left: 10px"
                    :disabled="!!formData.id"
                    >选择</el-button
                  >
                </div>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="销售类型" prop="saleType">
                <el-radio-group v-model="formData.saleType" disabled>
                  <el-radio :label="1">商城订单</el-radio>
                  <el-radio :label="2">线下订单</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>

            <el-col :span="6">
              <el-form-item label="销售订单号" prop="orderId">
                <el-input
                  v-model="formData.orderId"
                  autocomplete="off"
                  placeholder="请输入销售订单号"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="业务员" prop="saleName">
                <el-input v-model="formData.saleName" autocomplete="off" placeholder="请输入业务员" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="业务员电话" prop="saleMobile">
                <el-input
                  v-model="formData.saleMobile"
                  autocomplete="off"
                  placeholder="请输入业务员电话"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="下单时间" prop="createTime">
                <el-input
                  v-model="formData.createTime"
                  autocomplete="off"
                  placeholder="请输入下单时间"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="出货仓库" prop="deliverStorageName">
                <el-input
                  v-model="formData.deliverStorageName"
                  :disabled="true"
                  placeholder="请输入出货仓库"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item
                label="退货仓库"
                prop="storageStockId"
                :rules="joinCode == 'NO' ? [] : [{ required: true, message: '请选择退货仓库', trigger: 'change' }]"
              >
                <el-select v-model="formData.storageStockId" placeholder="请选择退货仓库" style="width: 100%">
                  <el-option
                    :label="item.storageName"
                    :value="item.storageId"
                    v-for="(item, index) in storageList"
                    :key="index"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="客户名称" prop="receUserName">
                <el-input
                  v-model="formData.receUserName"
                  autocomplete="off"
                  placeholder="请输入客户名称"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户电话" prop="recePhone">
                <el-input
                  v-model="formData.recePhone"
                  autocomplete="off"
                  placeholder="请输入客户电话"
                  disabled
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="地址" prop="receAddress">
                <el-input type="text" v-model="formData.receAddress" placeholder="详细地址" disabled></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="备注" prop="remark">
                <el-input
                  type="textarea"
                  v-model="formData.remark"
                  autocomplete="off"
                  placeholder="请输入备注"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-form-item label="附件" prop="fileUrl">
                <el-upload
                  class="avatar-uploader"
                  style="height: 122px"
                  :action="baseURL + 'common/upload'"
                  :headers="myHeaders"
                  :show-file-list="false"
                  :on-success="uploadSuccess"
                  :before-upload="beforeUpload"
                >
                  <img v-if="formData.fileUrl" :src="$showImgUrl(formData.fileUrl)" class="avatar" />
                  <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                </el-upload>
              </el-form-item>
            </el-col>
          </el-row>

          <el-tabs v-model="formTabs">
            <el-tab-pane label="商品信息" name="a"></el-tab-pane>
            <el-tab-pane label="条码信息" name="b" v-if="joinCode == 'CODE'"></el-tab-pane>
            <el-tab-pane label="旧机信息" name="c" v-if="formData.isReturnOld === 'YES'"></el-tab-pane>
          </el-tabs>

          <div v-show="formTabs == 'a'">
            <div style="margin-top: 10px" v-if="formData.isOld == 'YES'">
              <el-form-item label="是否退旧机" label-width="100px" prop="isReturnOld">
                <el-radio-group v-model="formData.isReturnOld">
                  <el-radio label="YES">是</el-radio>
                  <el-radio label="NO">否</el-radio>
                </el-radio-group>
              </el-form-item>
            </div>
            <el-table
              :data="goodsList"
              element-loading-text="Loading"
              border
              highlight-current-row
              stripe
              style="margin-top: 20px"
            >
              <el-table-column align="center" label="大类" prop="mainName" min-width="120"></el-table-column>
              <el-table-column align="center" label="小类" prop="smallName" min-width="120"></el-table-column>
              <el-table-column align="center" label="商品名称" prop="goodsName" min-width="200"></el-table-column>
              <el-table-column align="center" label="规格型号" prop="goodsSpecName" min-width="200">
                <template slot-scope="scope"> {{ scope.row.goodsSpecName }}{{ scope.row.goodsSpecValue }} </template>
              </el-table-column>
              <el-table-column align="center" label="单位" prop="goodsMaterialUnit" min-width="120">
                <template slot-scope="scope">
                  {{ scope.row.goodsMaterialUnit | unitFilter }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="退货数量" prop="waitRefundNum" min-width="120">
                <template slot-scope="scope">
                  {{ scope.row.waitRefundNum }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="退货单价" prop="waitRefundPrice" min-width="120">
                <template slot-scope="scope">
                  {{ scope.row.waitRefundPrice }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="退货金额" prop="amount" min-width="120">
                <template slot-scope="scope">
                  {{ (scope.row.waitRefundNum * scope.row.waitRefundPrice * 100) / 100 }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="已退数量" prop="" min-width="120">
                <template slot-scope="scope">
                  {{ 0 }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="已退单价" min-width="120">
                <template slot-scope="scope">
                  {{ 0 }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="已退金额" prop="" min-width="120">
                <template slot-scope="scope">
                  {{ 0 }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="订单数量" prop="num" min-width="120"></el-table-column>
              <el-table-column align="center" label="订单单价" prop="price" min-width="120"></el-table-column>
              <el-table-column align="center" label="订单金额" prop="payAmount" min-width="120"></el-table-column>

              <!-- <el-table-column align="center" label="操作" min-width="100" fixed="right" v-if="goodsList.length > 1">
                <template slot-scope="scope">
                  <el-popconfirm title="确定删除吗？" @confirm="deleteGoods(scope.$index)">
                    <el-button slot="reference" type="text">删除</el-button>
                  </el-popconfirm>
                </template>
              </el-table-column> -->
            </el-table>
          </div>
          <div v-show="formTabs == 'b'">
            <el-table
              :data="codeList"
              element-loading-text="Loading"
              border
              highlight-current-row
              stripe
              style="margin-top: 20px"
            >
              <el-table-column align="center" label="品牌" prop="brandName" min-width="120"></el-table-column>
              <el-table-column align="center" label="大类" prop="mainName" min-width="120"></el-table-column>
              <el-table-column align="center" label="小类" prop="smallName" min-width="120"></el-table-column>
              <el-table-column
                align="center"
                label="商品名称"
                prop="goodsMaterialName"
                min-width="200"
              ></el-table-column>
              <el-table-column align="center" label="规格型号" prop="specsName" min-width="200"></el-table-column>
              <el-table-column align="center" label="物料类型" prop="materialName" min-width="120"></el-table-column>
              <el-table-column
                align="center"
                label="物料名称"
                prop="goodsMaterialName"
                min-width="120"
              ></el-table-column>
              <el-table-column align="center" label="是否一物一码" prop="uniqueCode" min-width="120">
                <template slot-scope="scope">
                  {{ scope.row.uniqueCode == 'YES' ? '是' : '否' }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="条码" prop="materialCode" min-width="120"></el-table-column>
              <el-table-column align="center" label="数量" prop="stockQty" min-width="120"></el-table-column>
              <!-- <el-table-column align="center" label="操作" min-width="100" fixed="right" v-if="codeList.length > 1">
                <template slot-scope="scope">
                  <el-popconfirm title="确定删除吗？" @confirm="deleteCode(scope.$index)">
                    <el-button slot="reference" type="text">删除</el-button>
                  </el-popconfirm>
                </template>
              </el-table-column> -->
            </el-table>
          </div>
          <div v-show="formTabs == 'c'">
            <el-table
              :data="oldList"
              element-loading-text="Loading"
              border
              highlight-current-row
              stripe
              style="margin-top: 20px"
            >
              <el-table-column align="center" label="大类" prop="mainName" min-width="160"></el-table-column>
              <el-table-column align="center" label="小类" prop="smallName" min-width="160"></el-table-column>
              <el-table-column align="center" label="规格型号" prop="specName" min-width="160"></el-table-column>
              <el-table-column align="center" label="属性" prop="attrId" min-width="160">
                <template slot-scope="scope">
                  {{ scope.row.itemList.map(o => o.dictName).join('、') }}
                </template>
              </el-table-column>
              <el-table-column align="center" label="单位" min-width="120">
                <template>台</template>
              </el-table-column>
              <el-table-column align="center" label="数量" prop="num" min-width="120"></el-table-column>
              <el-table-column align="center" label="金额" prop="payAmount" min-width="120"></el-table-column>
            </el-table>
          </div>
        </el-form>
        <div slot="footer" class="dialog-footer" style="margin-top: 20px">
          <el-button size="mini" @click="data.removeTab()">取 消</el-button>
          <el-button size="mini" @click="formConfirm(data.removeTab)" type="primary">确 定</el-button>
        </div>
      </div>

      <div v-if="~['detail', 'examine'].indexOf(activeKey)" style="box-sizing: border-box; padding: 16px">
        <div style="font-weight: 500">单据信息</div>
        <el-divider></el-divider>

        <el-descriptions border title="" :column="3" :colon="false" labelStyle="width: 8%" contentStyle="width: 17%">
          <el-descriptions-item label="订单单号">
            {{ detailData.orderId }}
          </el-descriptions-item>
          <el-descriptions-item label="销售类型">
            {{ detailData.orderInfo.saleType | saleTypeFilter }}
          </el-descriptions-item>
          <el-descriptions-item label=""> </el-descriptions-item>
        </el-descriptions>
        <el-descriptions
          border
          title=""
          :column="3"
          :colon="false"
          labelStyle="width: 8%"
          contentStyle="width: 17%"
          style="margin-top: -1px"
        >
          <el-descriptions-item label="业务员">
            {{ detailData.orderInfo.saleName }}
          </el-descriptions-item>
          <el-descriptions-item label="业务员电话">
            {{ detailData.orderInfo.saleMobile }}
          </el-descriptions-item>
          <el-descriptions-item label="下单时间">
            {{ detailData.orderInfo.createTime }}
          </el-descriptions-item>
        </el-descriptions>
        <el-descriptions
          border
          title=""
          :column="3"
          :colon="false"
          labelStyle="width: 8%"
          contentStyle="width: 17%"
          style="margin-top: -1px"
        >
          <el-descriptions-item label="客户姓名">
            {{ detailData.orderInfo.receUserName }}
          </el-descriptions-item>
          <el-descriptions-item label="客户电话">
            {{ detailData.orderInfo.recePhone }}
          </el-descriptions-item>
          <el-descriptions-item label=""></el-descriptions-item>
        </el-descriptions>
        <el-descriptions
          border
          title=""
          :column="1"
          :colon="false"
          labelStyle="width: 8%"
          contentStyle="width: 92%"
          style="margin-top: -1px"
        >
          <el-descriptions-item label="地址">
            {{ detailData.orderInfo.receAddress }}
          </el-descriptions-item>
          <el-descriptions-item label="附件">
            <el-image
              v-if="detailData.fileUrls"
              style="width: 100px; height: 100px"
              :src="$showImgUrl(detailData.fileUrls)"
              :preview-src-list="[$showImgUrl(detailData.fileUrls)]"
            >
            </el-image>
          </el-descriptions-item>
          <el-descriptions-item label="备注">
            {{ detailData.remark }}
          </el-descriptions-item>
        </el-descriptions>

        <el-tabs v-model="detailTabs">
          <el-tab-pane label="商品信息" name="a"></el-tab-pane>
          <el-tab-pane label="条码信息" name="b" v-if="joinCode == 'CODE'"></el-tab-pane>
          <el-tab-pane label="旧机信息" name="c" v-if="detailData.isOld == 'YES'"></el-tab-pane>
        </el-tabs>

        <div v-show="detailTabs == 'a'">
          <el-table
            :data="detailData.orderOfflineRefundItems"
            element-loading-text="Loading"
            border
            highlight-current-row
            stripe
            style="margin-top: 20px"
          >
            <el-table-column align="center" label="大类" prop="mainName" min-width="120"></el-table-column>
            <el-table-column align="center" label="小类" prop="smallName" min-width="120"></el-table-column>
            <el-table-column align="center" label="商品名称" prop="goodsName" min-width="200"></el-table-column>
            <el-table-column align="center" label="规格型号" prop="goodsSpecName" min-width="200"></el-table-column>
            <el-table-column align="center" label="单位" prop="goodsMaterialUnit" min-width="120">
              <template slot-scope="scope">
                {{ scope.row.goodsMaterialUnit | unitFilter }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="退货数量" prop="refundNum" min-width="120"></el-table-column>
            <el-table-column align="center" label="退货单价" prop="refundAmount" min-width="120"></el-table-column>
            <el-table-column align="center" label="退货金额" prop="" min-width="120">
              <template slot-scope="scope">
                {{ (scope.row.refundAmount * scope.row.refundNum * 100) / 100 }}
              </template>
            </el-table-column>

            <el-table-column align="center" label="已退数量" prop="refundNum" min-width="120">
              <template slot-scope="scope">
                {{ detailData.examineStatus == 'OK' ? scope.row.refundNum : 0 }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="已退单价" prop="refundAmount" min-width="120">
              <template slot-scope="scope">
                {{ detailData.examineStatus == 'OK' ? scope.row.refundAmount : 0 }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="已退金额" min-width="120">
              <template slot-scope="scope">
                {{ detailData.examineStatus == 'OK' ? (scope.row.refundAmount * scope.row.refundNum * 100) / 100 : 0 }}
              </template>
            </el-table-column>

            <el-table-column align="center" label="订单数量" prop="num" min-width="120"></el-table-column>
            <el-table-column align="center" label="订单单价" prop="price" min-width="120"></el-table-column>
            <el-table-column align="center" label="订单金额" prop="payAmount" min-width="120"></el-table-column>
          </el-table>
        </div>
        <div v-show="detailTabs == 'b'">
          <el-table
            :data="detailData.orderOfflineItemCodes"
            element-loading-text="Loading"
            border
            highlight-current-row
            stripe
            style="margin-top: 20px"
          >
            <el-table-column align="center" label="品牌" prop="brandName" min-width="120"></el-table-column>
            <el-table-column align="center" label="大类" prop="mainName" min-width="120"></el-table-column>
            <el-table-column align="center" label="小类" prop="smallName" min-width="120"></el-table-column>
            <el-table-column align="center" label="商品名称" prop="goodsMaterialName" min-width="200"></el-table-column>
            <el-table-column align="center" label="规格型号" prop="specsName" min-width="200"></el-table-column>
            <el-table-column align="center" label="物料类型" prop="materialName" min-width="120"></el-table-column>
            <el-table-column align="center" label="物料名称" prop="goodsMaterialName" min-width="120"></el-table-column>
            <el-table-column align="center" label="是否一物一码" prop="uniqueCode" min-width="120">
              <template slot-scope="scope">
                {{ scope.row.uniqueCode == 'YES' ? '是' : '否' }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="条码" prop="materialCode" min-width="120"></el-table-column>
            <el-table-column align="center" label="数量" prop="stockQty" min-width="120"></el-table-column>
          </el-table>
        </div>
        <div v-show="detailTabs == 'c'">
          <el-table
            :data="detailData.orderOldProductDTOList"
            element-loading-text="Loading"
            border
            highlight-current-row
            stripe
            style="margin-top: 20px"
          >
            <el-table-column align="center" label="大类" prop="mainName" min-width="160"></el-table-column>
            <el-table-column align="center" label="小类" prop="smallName" min-width="160"></el-table-column>
            <el-table-column align="center" label="规格型号" prop="specName" min-width="160"></el-table-column>
            <el-table-column align="center" label="属性" prop="attrId" min-width="160">
              <template slot-scope="scope">
                {{ scope.row.itemList.map(o => o.dictName).join('、') }}
              </template>
            </el-table-column>
            <el-table-column align="center" label="单位" min-width="120">
              <template>台</template>
            </el-table-column>
            <el-table-column align="center" label="数量" prop="num" min-width="120"></el-table-column>
            <el-table-column align="center" label="金额" prop="payAmount" min-width="120"></el-table-column>
          </el-table>
        </div>

        <div slot="footer" class="dialog-footer" style="margin-top: 20px">
          <el-button size="mini" @click="data.removeTab()">关 闭</el-button>
          <el-button
            size="mini"
            @click="detailConfirm(data.removeTab, 'FAIL')"
            type="danger"
            v-if="activeKey == 'examine'"
            >审核驳回</el-button
          >
          <el-button
            size="mini"
            @click="detailConfirm(data.removeTab, 'OK')"
            type="primary"
            v-if="activeKey == 'examine'"
            >审核通过</el-button
          >
        </div>
      </div>

      <el-dialog
        title="选择发货单"
        :visible.sync="isShowOrderDialog"
        :close-on-click-modal="false"
        :show-close="false"
        width="1200px"
      >
        <div class="screen-container">
          <el-form ref="screenForm" :model="screenForm" label-width="90px" size="small" label-position="left">
            <el-row :gutter="20">
              <el-col :span="8">
                <el-form-item label="销售订单号" prop="orderId">
                  <el-input v-model="screenForm.orderId" placeholder="请输入销售订单号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8">
                <el-form-item label="发货单号" prop="deliveryId">
                  <el-input v-model="screenForm.deliveryId" placeholder="请输入发货单号"></el-input>
                </el-form-item>
              </el-col>
              <el-col :span="8" class="tr">
                <el-form-item label="">
                  <el-button size="small" type="primary" @click="submitScreenForm">搜索</el-button>
                  <el-button size="small" @click="resetScreenForm">清空</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
        </div>

        <div class="table" style="margin: 10px 0 20px">
          <el-table
            border
            :data="orderList"
            element-loading-text="Loading"
            tooltip-effect="dark"
            style="width: 100%"
            max-height="270"
            @selection-change="handleChooseGoods"
          >
            <el-table-column align="center" type="selection" width="45"></el-table-column>
            <el-table-column align="center" prop="deliveryId" label="发货单号" min-width="180"></el-table-column>
            <el-table-column align="center" prop="orderId" label="销售订单号" min-width="180"></el-table-column>
            <el-table-column align="center" prop="status" label="状态" min-width="80">
              <template slot-scope="scope">
                {{
                  { SEND: '已发货', REFUND: '已退货', PART_REFUND: '部分退货', REFUND_PRICE: '仅退款' }[
                    scope.row.status
                  ]
                }}
              </template>
            </el-table-column>
            <el-table-column prop="sendNum" align="center" label="发货数量"></el-table-column>
            <el-table-column prop="refundNum" align="center" label="退货数量"></el-table-column>
            <el-table-column prop="num" align="center" label="订单数量"></el-table-column>
            <el-table-column prop="sendInsideCodeQty" align="center" label="内机数量"></el-table-column>
            <el-table-column prop="sendOutCodeQty" align="center" label="外机数量"></el-table-column>
            <el-table-column prop="sendPartsCodeQty" align="center" label="配件数量"></el-table-column>
            <el-table-column prop="storageStockName" align="center" label="发货仓库" width="100"></el-table-column>
            <el-table-column prop="pickType" align="center" label="发货方式">
              <template slot-scope="scope">
                {{ scope.row.pickType == 'YES' ? '自提' : '快递物流' }}
              </template>
            </el-table-column>
            <el-table-column prop="logisticsNo" align="center" label="快递单号" width="100"></el-table-column>
            <el-table-column prop="companyName" align="center" label="物流公司" width="100"></el-table-column>
            <el-table-column prop="pickName" align="center" label="提货人"></el-table-column>
            <el-table-column prop="pickPhone" align="center" label="提货人电话" width="110"></el-table-column>
            <el-table-column align="center" prop="deliverTime" label="发货时间" min-width="160"></el-table-column>
            <el-table-column prop="createBy" align="center" label="操作人" width="140"></el-table-column>
            <el-table-column prop="createTime" align="center" label="操作时间" width="160"></el-table-column>
          </el-table>
        </div>
        <div class="pagination clearfix">
          <div class="fr">
            <el-pagination
              @size-change="handleSizeChange"
              @current-change="handleCurrentChange"
              :current-page="currentPage"
              :page-sizes="[10, 20, 30, 50]"
              :page-size="10"
              background
              layout="prev, pager, next"
              :total="listTotal"
            >
            </el-pagination>
          </div>
        </div>

        <span slot="footer" class="dialog-footer">
          <el-button @click="isShowOrderDialog = false">关 闭</el-button>
          <el-button type="primary" @click="confirmOrderDialog">确 定</el-button>
        </span>
      </el-dialog>
    </template>
  </zj-tab-page>
</template>

<script>
import { mapGetters } from 'vuex'
import { getToken } from '@/utils/auth'
import TemplatePage from '@/components/template/template-page-1.vue'
import import_mixin from '@/components/template/import_mixin.js'
import {
  getSalesReturnOrderList,
  salesReturnOrderListExport,
  salesReturnOrderSave,
  getSalesReturnOrderDetail,
  salesReturnOrderExamine,
  getOrderTypeList,
  getSalesDeliverOrderList,
  getOrderCodeList,
  getOrderDetail,
  getSalesDeliverOrderDetail
} from '@/api/order'
import operation_mixin from '@/components/template/operation_mixin.js'
import geographicalPosi from '@/components/geographicalPosi/index.vue'
import * as Storage from '@/api/storage'

export default {
  components: { TemplatePage, geographicalPosi },
  mixins: [import_mixin, operation_mixin],
  filters: {
    saleTypeFilter(val) {
      const MAP = {
        1: '商城销售',
        2: '线下销售'
      }
      return MAP[val]
    },
    unitFilter(val) {
      const MAP = {
        C: '整套',
        I: '单个'
      }
      return MAP[val]
    },
    payTypeFilter(val) {
      const MAP = {
        WECHAT: '微信支付',
        CASH: '现金支付',
        TRANSFER: '转账支付'
      }
      return MAP[val]
    },
    examineStatusFilter(val) {
      const MAP = {
        WAIT: '待审批',
        OK: '审批通过',
        FAIL: '审批驳回'
      }
      return MAP[val]
    }
  },
  data() {
    return {
      baseURL: process.env.VUE_APP_BASE_API,
      myHeaders: { 'x-token': getToken() },
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: false
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      // 勾选选中行
      recordSelected: [],
      /** 表单变量 */
      formDialogType: 0,
      formDialogTitles: ['新增', '编辑'],
      formDialog: false,
      formData: {
        id: '',
        companyWechatName: '',
        orderId: '',
        saleType: '',
        saleName: '', // 业务员
        saleMobile: '', // 业务员电话
        orderSmallType: '', // 工单类型
        createTime: '',
        receUserName: '',
        recePhone: '',
        receAddress: '',

        remark: '', // 备注
        fileUrl: '', // 附件

        isOld: 'NO',
        isReturnOld: '',

        deliverStorageName: '',
        storageStockId: ''
      },
      formRules: {
        isReturnOld: [{ required: true, message: '请选择是否退旧机', trigger: 'change' }]
        // storageStockId: [{ required: true, message: '请选择退货仓库', trigger: 'change' }],
      },
      formType: 'add',
      formVisible: false,

      examineStatus: '',
      orderTypeList: [],
      storageList: [],
      goodsList: [],
      codeList: [],
      oldList: [],
      formTabs: 'a',
      detailTabs: 'a',

      detailData: {},

      pageType: '',

      isShowOrderDialog: false,
      screenForm: {
        orderId: '',
        deliveryId: '',
        goodsName: ''
      },
      currentPage: 1, // 当前页码
      pageSize: 10, // 每页数量
      listTotal: 0, // 列表总数
      orderList: [],
      waitChooseOrder: [],

      joinCode: JSON.parse(localStorage.getItem('greemall_user')).joinCode
    }
  },
  computed: {
    ...mapGetters(['name']),
    // 事件组合
    optionsEvensGroup() {
      return [
        [
          [
            this.optionsEvensAuth('add', {
              click: () => {
                this.openForm('add')
              }
            })
          ]
        ]
      ]
    },
    // 更多参数
    moreParameters() {
      return []
    },
    formItems() {
      return []
    }
  },

  created() {
    if (this.$route.query.deliverId) {
      this.$nextTick(() => {
        this.openForm('add')
        getSalesDeliverOrderDetail({ deliveryId: this.$route.query.deliverId }).then(res => {
          const dData = res.data
          this.formData.deliveryId = dData.deliveryId
          this.formData.deliverStorageName = dData.storageStockName
          dData.orderDetailSendList.forEach(item => {
            item.waitRefundNum = item.sendNum
            item.waitRefundPrice = item.price
          })
          this.goodsList = dData.orderDetailSendList
          getOrderDetail({ orderId: dData.orderId }).then(res => {
            const oData = res.data
            this.formData.orderId = oData.orderId
            this.formData.isOld = oData.isOld
            this.formData.saleType = oData.saleType
            this.formData.saleName = oData.saleName
            this.formData.saleMobile = oData.saleMobile
            this.formData.createTime = oData.createTime
            this.formData.receUserName = oData.receUserName
            this.formData.recePhone = oData.recePhone
            this.formData.receAddress = oData.receAddress
            this.oldList = oData.orderOldProductDTOList
          })
          getOrderCodeList({ deliveryId: dData.deliveryId }).then(res => {
            this.codeList = res.data
          })
        })
      })
    }
    if (this.$route.query.refundId) {
      this.$nextTick(() => {
        this.openDetail('detail', this.$route.query.refundId)
      })
    }
  },

  methods: {
    // 列表请求函数
    // getList: getSalesReturnOrderList,
    getList(p) {
      try {
        var pam = JSON.parse(JSON.stringify(p))
        if (this.examineStatus) {
          pam.params.push({ param: 'a.examine_status', compare: '=', value: this.examineStatus })
        }
        return getSalesReturnOrderList(pam)
      } catch (error) {
        console.log(error)
      }
    },
    // 列表导出函数
    exportList: salesReturnOrderListExport,
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      return defaultData
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    // 切换状态
    changeType(val) {
      this.$refs.pageRef.refreshList()
    },
    // 表格操作列
    operation() {
      return this.operationBtn({
        edit: {
          conditions: ({ row, index, column }) => {
            return row.examineStatus != 'OK' && row.examineStatus != 'FAIL'
          },
          btnType: 'text',
          click: ({ row, index, column }) => {
            this.openForm('edit', row.id)
          }
        },
        detail: {
          btnType: 'text',
          click: ({ row, index, column }) => {
            this.openDetail('detail', row.id)
          }
        },
        examine: {
          conditions: ({ row, index, column }) => {
            return row.examineStatus === 'WAIT'
          },
          btnType: 'text',
          click: ({ row, index, column }) => {
            this.openDetail('examine', row.id)
          }
        }
      })
    },
    openForm(type, id) {
      this.$refs.tabPage.addTab({
        // 对应显示的模块
        activeKey: type,
        // 唯一标识
        key: type,
        // 页签名称
        label: { add: '新增', edit: '编辑' }[type],
        // 打开时事件
        triggerEvent: () => {
          this.pageType = type
          this.formCancel()
          this.$nextTick(() => {
            // this.getOrderTypeList();
            this.getStorageList()
            this.formType = type
            this.formVisible = true
            this.formTabs = 'a'
            if (type == 'add') {
              this.formDialogType = 0
              this.formData.companyWechatName = this.name
            } else if (type == 'edit') {
              this.formDialogType = 1
              getSalesReturnOrderDetail({ id }).then(res => {
                const data = res.data
                this.formData.id = data.id
                this.formData.deliveryId = data.deliveryId
                this.formData.companyWechatName = data.companyWechatName
                this.formData.orderId = data.orderId
                this.formData.storageStockId = data.storageStockId
                this.formData.storageStockName = data.storageStockName
                this.formData.saleType = data.orderInfo.saleType
                this.formData.saleName = data.orderInfo.saleName
                this.formData.saleMobile = data.orderInfo.saleMobile
                this.formData.createTime = data.orderInfo.createTime
                this.formData.receUserName = data.orderInfo.receUserName
                this.formData.recePhone = data.orderInfo.recePhone
                this.formData.receAddress = data.orderInfo.receAddress
                this.formData.deliverStorageName = data.storageName

                this.formData.remark = data.remark
                this.formData.fileUrl = data.fileUrls

                data.orderOfflineRefundItems.forEach(item => {
                  item.waitRefundNum = item.refundNum
                  item.waitRefundPrice = item.price
                  item.refundNum = item.retiredNum
                  // item.refundAmount = item.retiredAmount;
                  item.refundAmount = item.payAmount
                })

                this.goodsList = data.orderOfflineRefundItems
                this.codeList = data.orderOfflineItemCodes
                // Object.assign(this.formData, res.data)

                this.formData.isReturnOld = data.isOld
                this.oldList = data.orderOldProductDTOList
              })
            }
          })
        },
        // 关闭时事件
        closeEvent: () => {
          this.formCancel()
        }
      })
    },
    formCancel() {
      this.formVisible = false
      this.$refs?.formRef?.resetFields()
      this.formData.id = ''
      this.formData.orderId = ''
      this.formData.fileUrl = ''
      this.goodsList = []
      this.$data.formRef = this.$options.data().formRef
    },
    formConfirm(cancel) {
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          // if(!this.formData.storageStockId) return this.$errorMsg('请选择退货仓库');

          salesReturnOrderSave({
            id: this.formData.id || '',
            deliveryId: this.formData.deliveryId,
            orderId: this.formData.orderId,
            remark: this.formData.remark,
            fileUrls: this.formData.fileUrl,
            orderOfflineRefundItems: this.goodsList.map(item => {
              return {
                orderId: this.formData.orderId,
                orderDetailId: item.orderDetailId,
                refundNum: item.waitRefundNum,
                refundAmount: item.waitRefundPrice
              }
            }),
            orderOfflineItemCodes: this.joinCode == 'CODE' ? this.codeList : [],
            isOld: this.formData.isReturnOld,
            ids: this.oldList.map(o => o.id),
            storageStockId: this.formData.storageStockId || '',
            storageStockName: this.formData.storageStockId
              ? this.storageList.find(o => o.storageId == this.formData.storageStockId).storageName
              : ''
          }).then(res => {
            this.$message({ type: 'success', message: `${this.formDialogTitles[this.formDialogType]}成功!` })
            cancel('list')
            this.$refs.pageRef.refreshList()
          })
        }
      })
    },

    openDetail(type, id) {
      this.$refs.tabPage.addTab({
        // 对应显示的模块
        activeKey: type,
        // 唯一标识
        key: type,
        // 页签名称
        label: { detail: '详情', examine: '审核' }[type],
        // 打开时事件
        triggerEvent: () => {
          this.pageType = type
          this.formCancel()
          this.$nextTick(() => {
            this.detailTabs = 'a'
            if (type == 'detail') {
              this.formDialogType = 0
            } else if (type == 'examine') {
              this.formDialogType = 1
            }
            getSalesReturnOrderDetail({ id }).then(res => {
              this.detailData = res.data
            })
          })
        },
        // 关闭时事件
        closeEvent: () => {
          this.detailCancel()
        }
      })
    },
    detailCancel() {
      this.formVisible = false
    },
    detailConfirm(cancel, status) {
      salesReturnOrderExamine({
        id: this.detailData.id,
        examineStatus: status
      }).then(res => {
        this.$message({ type: 'success', message: `审批成功!` })
        cancel('list')
        this.$refs.pageRef.refreshList()
      })
    },

    // 附件 - 上传成功
    uploadSuccess(res, file) {
      this.formData.fileUrl = res.data.url
    },

    // 附件 - 上传前
    beforeUpload(file) {
      const fileSuffix = file.name.substring(file.name.lastIndexOf('.') + 1)
      const whiteList = ['jpg', 'jpeg', 'png']
      if (whiteList.indexOf(fileSuffix) === -1) {
        this.$errorMsg('只支持上传jpg/png文件!')
        return false
      }
    },

    openOrderDialog() {
      this.getOrderList()
      this.isShowOrderDialog = true
    },

    // table点击选择商品
    handleChooseGoods(val) {
      this.waitChooseOrder = val
    },

    getStorageList() {
      Storage.getList({ pageNum: 1, pageSize: -1, type: '商品' }).then(res => {
        this.storageList = res.data.records
      })
    },

    getOrderList() {
      getSalesDeliverOrderList({
        pageNum: this.currentPage,
        pageSize: this.pageSize,
        params: [
          { param: 'a.order_id', compare: 'like', value: this.screenForm.orderId },
          { param: 'a.delivery_id', compare: 'like', value: this.screenForm.deliveryId },
          { param: 'b.goods_name', compare: 'like', value: this.screenForm.goodsName },
          { param: 'a.status', compare: '=', value: 'SEND' }
        ]
      }).then(res => {
        this.orderList = res.data.records
        this.listTotal = res.data.total
      })
    },

    // 更改每页数量
    handleSizeChange(val) {
      this.pageSize = val
      this.currentPage = 1
      this.getOrderList()
    },

    // 更改当前页
    handleCurrentChange(val) {
      this.currentPage = val
      this.getOrderList()
    },

    // 提交筛选表单
    submitScreenForm() {
      this.currentPage = 1
      this.getOrderList()
    },

    // 重置筛选表单
    resetScreenForm() {
      this.$refs.screenForm.resetFields()
      this.currentPage = 1
      this.getOrderList()
    },

    confirmOrderDialog() {
      if (this.waitChooseOrder.length < 1) {
        return this.$errorMsg('请选择发货单')
      }
      if (this.waitChooseOrder.length > 1) {
        return this.$errorMsg('最多选择一个发货单')
      }
      getSalesDeliverOrderDetail({ deliveryId: this.waitChooseOrder[0].deliveryId }).then(res => {
        const data = res.data
        this.formData.deliveryId = data.deliveryId
        this.formData.deliverStorageName = data.storageStockName
        data.orderDetailSendList.forEach(item => {
          item.waitRefundNum = item.sendNum
          item.waitRefundPrice = item.price
        })
        this.goodsList = data.orderDetailSendList
      })
      getOrderDetail({ orderId: this.waitChooseOrder[0].orderId }).then(res => {
        const data = res.data
        this.formData.orderId = data.orderId
        this.formData.isOld = data.isOld
        this.formData.saleType = data.saleType
        this.formData.saleName = data.saleName
        this.formData.saleMobile = data.saleMobile
        this.formData.createTime = data.createTime
        this.formData.receUserName = data.receUserName
        this.formData.recePhone = data.recePhone
        this.formData.receAddress = data.receAddress
        // data.orderDetails.forEach(item => {
        //   item.waitRefundNum = item.num;
        //   item.waitRefundPrice = item.price;
        // })
        // this.goodsList = data.orderDetails;
        this.oldList = data.orderOldProductDTOList

        getOrderCodeList({ deliveryId: this.waitChooseOrder[0].deliveryId }).then(res => {
          this.codeList = res.data
        })

        this.isShowOrderDialog = false
      })
    },

    // 删除商品
    deleteGoods(index) {
      this.goodsList.splice(index, 1)
    },

    // 删除条码
    deleteCode(index) {
      this.codeList.splice(index, 1)
    },

    // 删除旧机
    deleteOld(index) {
      this.oldList.splice(index, 1)
    },

    // 获取工单类型列表
    getOrderTypeList() {
      getOrderTypeList({
        pageNum: 1,
        pageSize: -1,
        params: [{ param: 'a.status', compare: '=', value: true }]
      }).then(res => {
        this.orderTypeList = res.data.records
      })
    }
  }
}
</script>

<style lang="scss">
.specTable .el-table__cell {
  padding: 0 !important;
}

// 图片墙
.el-upload-list--picture-card .el-upload-list__item {
  width: 100px;
  height: 100px;
}

.el-upload--picture-card {
  width: 100px;
  height: 100px;
  line-height: 100px;

  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 100px;
    line-height: 100px;
    text-align: center;
  }
}
</style>
