<template>
  <div class="detail-container">
    <el-page-header @back="goBack" content="退货"></el-page-header>

    <div class="main-title">
      <div class="title">退货申请</div>
    </div>
    <el-form
      ref="mainForm"
      :model="mainForm"
      :rules="mainFormRules"
      label-width="90px"
      size="small"
      label-position="right"
    >
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="退货单号" prop="orderNum">
            <el-input v-model="mainForm.orderNum" placeholder="系统自动生成" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="制单人" prop="createMan">
            <el-input v-model="mainForm.createMan" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="8" style="height: 51px">
          <el-form-item label="单据日期" prop="date">
            <el-date-picker
              v-model="mainForm.date"
              type="date"
              value-format="yyyy-MM-dd"
              style="width: 100%"
              placeholder="选择日期"
            >
            </el-date-picker>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :lg="8">
          <el-form-item label="经销商编号" prop="jxsNum">
            <el-input v-model="mainForm.jxsNum" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="16">
          <el-form-item label="经销商名称" prop="jxsName">
            <el-input v-model="mainForm.jxsName" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="mainForm.remark" placeholder="请输入备注"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div class="main-title">
      <el-button type="primary" size="small" icon="el-icon-plus" @click="openDialog">添加引用</el-button>
    </div>
    <div class="table">
      <el-table :data="goodsList" element-loading-text="Loading" border fit highlight-current-row stripe>
        <el-table-column align="center" label="序号" type="index" width="50"></el-table-column>
        <el-table-column
          align="center"
          label="发货单号"
          prop="id"
          min-width="200"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          label="销售类型"
          prop="saleTypeName"
          min-width="100"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          label="发货仓库"
          prop="correspondName"
          min-width="100"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          label="销售订单号"
          prop="mainOrderId"
          min-width="200"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          label="产品编码"
          prop="materialCode"
          min-width="160"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          label="产品名称"
          prop="materialName"
          min-width="160"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          label="规格型号"
          prop="specification"
          min-width="160"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          label="单位"
          prop="unit"
          min-width="100"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column
          align="center"
          label="数量"
          prop="approvalNumber"
          min-width="100"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column align="center" label="出货状态" prop="shipStatus" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.shipStatus | chStatusFilter }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="开票状态" prop="billStatus" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            {{ scope.row.billStatus | kpStatusFilter }}
          </template>
        </el-table-column>
        <el-table-column align="center" label="是否退货" prop="isReturn" min-width="100">
          <template slot-scope="scope">
            <el-checkbox v-model="scope.row.isReturn"></el-checkbox>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="可退数量"
          prop="refundableQty"
          min-width="100"
          show-overflow-tooltip
        ></el-table-column>
        <el-table-column align="center" label="退货数量" prop="num" min-width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.num" size="small" type="number" @mousewheel.native.prevent></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="备注" prop="remark" min-width="160" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.remark" size="small"></el-input>
          </template>
        </el-table-column>
      </el-table>
    </div>

    <div class="page-footer">
      <div class="footer" :class="classObj">
        <el-button type="primary" @click="clickSubmitForm" :loading="formLoading">{{
          formLoading ? '提交中 ...' : '提 交'
        }}</el-button>
        <el-popconfirm title="确定关闭吗？" @confirm="goBack" style="margin-left: 10px">
          <el-button slot="reference">关 闭</el-button>
        </el-popconfirm>
      </div>
    </div>

    <el-dialog title="添加引用" :visible.sync="isShowDialog" width="80%">
      <el-form ref="screenForm" :model="screenForm" size="small" label-position="left" label-width="70px">
        <el-row :gutter="20">
          <el-col :xs="12" :sm="6" :lg="6">
            <el-form-item prop="orderNum" label="发货单号">
              <el-input v-model="screenForm.orderNum" placeholder="请输入发货单号"></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :xs="12" :sm="6" :lg="6">
            <el-form-item prop="dealer" label="经销商">
              <el-select v-model="screenForm.dealer" placeholder="请选择经销商" style="width: 100%;" filterable clearable>
                <el-option :label="item.name" :value="item.id" v-for="(item, index) in dealerList" :key="index"></el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
          <el-col :xs="12" :sm="6" :lg="6">
            <el-form-item label="">
              <el-button size="small" @click="resetScreenForm">清空</el-button>
              <el-button size="small" type="primary" @click="submitScreenForm">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="table">
        <el-table
          :data="tableGoodsList"
          element-loading-text="Loading"
          border
          fit
          highlight-current-row
          stripe
          height="400"
          @selection-change="tableSelectionChange"
        >
          <el-table-column align="center" type="selection" width="55" :selectable="checkboxSelect"></el-table-column>
          <el-table-column
            align="center"
            label="发货单号"
            prop="id"
            min-width="200"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            align="center"
            label="销售类型"
            prop="saleTypeName"
            min-width="100"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            align="center"
            label="发货仓库"
            prop="correspondName"
            min-width="100"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            align="center"
            label="销售订单号"
            prop="mainOrderId"
            min-width="200"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            align="center"
            label="经销商编码"
            prop="customerNumber"
            min-width="140"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            align="center"
            label="经销商名称"
            prop="customerName"
            min-width="160"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            align="center"
            label="产品编码"
            prop="materialCode"
            min-width="160"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            align="center"
            label="产品名称"
            prop="materialName"
            min-width="160"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            align="center"
            label="规格型号"
            prop="specification"
            min-width="160"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            align="center"
            label="单位"
            prop="unit"
            min-width="100"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column
            align="center"
            label="数量"
            prop="approvalNumber"
            min-width="100"
            show-overflow-tooltip
          ></el-table-column>
          <el-table-column align="center" label="出货状态" prop="shipStatus" min-width="100" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.shipStatus | chStatusFilter }}
            </template>
          </el-table-column>
          <el-table-column align="center" label="开票状态" prop="billStatus" min-width="100" show-overflow-tooltip>
            <template slot-scope="scope">
              {{ scope.row.billStatus | kpStatusFilter }}
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="可退数量"
            prop="refundableQty"
            min-width="100"
            show-overflow-tooltip
          ></el-table-column>
        </el-table>
        <div class="pagination clearfix" style="margin-top: 10px">
          <div class="fr">
            <el-pagination
              @current-change="handleTableCurrentChange"
              :current-page="currentPage"
              :page-size="10"
              background
              layout="prev, pager, next"
              :total="listTotal"
            >
            </el-pagination>
          </div>
        </div>
      </div>

      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitAddGoods">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getDetail, getGoodsList, addData } from '@/api/supply/return'
import { getDealerList } from '@/api/common'

export default {
  name: 'ReturnForm',
  componentName: 'ReturnForm',
  props: ['listItem'],
  filters: {
    chStatusFilter(val) {
      const MAP = {
        0: '未出货',
        1: '已出货'
      }
      return MAP[val]
    },
    kpStatusFilter(val) {
      const MAP = {
        0: '未开票',
        1: '已开票'
      }
      return MAP[val]
    }
  },
  data() {
    return {
      detailData: {},
      formLoading: false,
      mainForm: {
        orderNum: '',
        createMan: '',
        date: '',
        jxsNum: '',
        jxsName: '',
        remark: ''
      },
      mainFormRules: {
        date: [{ required: true, message: '请选择单据日期', trigger: 'change' }]
      },
      goodsList: [],

      isShowDialog: false,
      screenForm: {
        orderNum: '',
        dealer: ''
      },
      currentPage: 1,
      listTotal: 0,
      dealerList: [],

      tableGoodsList: [],
      tableSelection: []
    }
  },

  computed: {
    sidebar() {
      return this.$store.state.app.sidebar
    },
    classObj() {
      return {
        hideSidebar: !this.sidebar.opened,
        openSidebar: this.sidebar.opened
      }
    }
  },

  created() {
    if (this.listItem) {
      this.getDetail()
    } else {
      this.mainForm.jxsNum = JSON.parse(localStorage.getItem('supply_user')).customerNumber
      this.mainForm.jxsName = JSON.parse(localStorage.getItem('supply_user')).customerName
      this.mainForm.createMan = JSON.parse(localStorage.getItem('supply_user')).nickName
    }
  },

  methods: {
    // 返回列表
    goBack() {
      this.$emit('backListFormDetail')
    },

    // 获取经销商列表
    getDealerList() {
      getDealerList({
        pageNum: 1,
        pageSize: -1
      }).then(res => {
        this.dealerList = res.data.records
      })
    },

    // 获取详情
    getDetail() {
      getDetail({ id: this.listItem.id }).then(res => {
        this.detailData = res.data
      })
    },

    // 获取商品列表
    getGoodsList() {
      getGoodsList({
        pageNum: this.currentPage,
        pageSize: 10,
        customerId: this.screenForm.dealer,
        id: this.screenForm.orderNum
      }).then(res => {
        res.data.records.forEach(item => {
          item.num = ''
          item.remark = ''
          item.isReturn = true
        })
        let oldGoodsList = this.goodsList
        let newGoodsList = res.data.records
        for (let i = 0; i < oldGoodsList.length; i++) {
          let oldItem = oldGoodsList[i]
          for (let j = 0; j < newGoodsList.length; j++) {
            let newItem = newGoodsList[j]
            if (newItem.materialId === oldItem.materialId) {
              newGoodsList[j].selected = true
              break
            }
          }
        }

        this.tableGoodsList = newGoodsList
        this.listTotal = res.data.total
      })
    },

    // 查询重复值并禁选
    checkboxSelect(row, rowIndex) {
      if (row.selected) {
        return false // 禁用
      } else {
        return true // 不禁用
      }
    },

    // 点击 选择商品
    openDialog() {
      this.isShowDialog = true
      this.getDealerList()
      if (this.screenForm.orderNum) {
        this.getGoodsList()
      }
    },

    // 提交筛选表单
    submitScreenForm() {
      if (!this.screenForm.orderNum) {
        return this.$errorMsg('请填写发货申请单号')
      }
      // if(!this.screenForm.dealer) {
      //   return this.$errorMsg('请选择经销商');
      // }
      this.currentPage = 1
      this.getGoodsList()
    },

    // 重置筛选表单
    resetScreenForm() {
        this.$refs.screenForm.resetFields()
      this.currentPage = 1
      this.tableGoodsList = []
      // this.getGoodsList();
    },

    // 更改列表当前页
    handleTableCurrentChange(val) {
      if (this.tableSelection.length > 0) {
        return this.$errorMsg('已选择产品不可切换')
      }
      this.currentPage = val
      this.getGoodsList()
    },

    // 关闭 弹窗
    closeDialog() {
      this.isShowDialog = false
    },

    // 列表选择
    tableSelectionChange(val) {
      this.tableSelection = val
    },

    // 确定 添加产品
    submitAddGoods() {
      this.goodsList = this.goodsList.concat(this.tableSelection)
      this.isShowDialog = false
    },

    // 删除产品
    deleteItem(index) {
      this.goodsList.splice(index, 1)
    },

    clickSubmitForm() {
      this.$refs.mainForm.validate(valid => {
        if (valid) {
          if (this.goodsList.length < 1) {
            return this.$errorMsg('请添加引用')
          }
          for (let i = 0; i < this.goodsList.length; i++) {
            if (!this.goodsList[i].num) {
              this.$errorMsg('请输入退货数量')
              return
            }
            if (this.goodsList[i].num > this.goodsList[i].refundableQty) {
              this.$errorMsg('退货数量不能大于可退数量')
              return
            }
          }

          let goodsList = this.goodsList.filter(item => {
            return item.isReturn
          })
          goodsList = goodsList.map(item => {
            return {
              invoiceOrderId: item.invoiceOrderId,
              num: item.num,
              remark: item.remark,
              correspondId: item.correspondId,
              correspondName: item.correspondName
            }
          })
          let params = {
            retreatTime: this.mainForm.date + ' 00:00:00',
            remark: this.mainForm.remark,
            retreatDocumentOrder: goodsList
          }
          addData(params).then(res => {
            this.$successMsg('添加成功')
            this.goBack()
          })
        }
      })
    }
  }
}
</script>

<style scoped lang="scss">
.detail-container {
  width: 100%;
  height: 100%;
}
.main-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-top: 30px;
  height: 60px;
  border-bottom: 1px solid #dcdfe6;
  margin-bottom: 20px;
  .title {
    font-size: 16px;
    font-weight: 600;
    padding-left: 10px;
  }
}
</style>
