<template>
  <div class="bg-in-stock">
    <el-form ref="orderReturnAddForm" :model="orderReturnAddForm" label-width="120px" inline style="width: 100%;">
      <h3>退货单</h3>
      <el-form-item label="退货时间:" prop="return_time">
        <el-date-picker v-if="type !== 'detail'" v-model="orderReturnAddForm.return_time" value-format="yyyy-MM-dd HH:mm:ss" type="datetime"
          placeholder="选择日期时间">
        </el-date-picker>
      <span v-else>{{ orderReturnAddForm.return_time }}</span>
      </el-form-item>
      <el-form-item label="订单:" style="white-space: nowrap;">
        <!-- <el-button v-if="type !== 'detail' || orderReturnAddForm.sn==''" class="button" size="mini" type="primary" @click="handleSelectOrderSn"
          :disabled="type === 'audit'">选择</el-button> -->
        <span v-if="orderReturnAddForm.sn">{{ orderReturnAddForm.sn }}</span>
      </el-form-item>
      <el-form-item></el-form-item>
      <el-form-item label="退货说明:" prop="return_remark" style="width: 900px">
        <el-input style="width:525px" v-model="orderReturnAddForm.return_remark" v-if="type !== 'detail'" type="textarea"
          :disabled="type === 'detail' || type === 'audit'" :autosize="{ minRows: 3, maxRows: 4 }"
          placeholder="请输入退货说明"></el-input>
          <span v-else>{{ orderReturnAddForm.return_remark }}</span>
      </el-form-item>
      <div class="mx">
        <h3>退货明细</h3>
      </div>
      <div>
        <el-form-item style="width: 100%;">
          <el-table :data="orderReturnAddForm.item_list" border :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ textAlign: 'center' }" style="width: 100%; margin-top: 20px;">
            <el-table-column label="商品编号">
              <template slot-scope="scope">
                {{ scope.row.goods_vo.sn }}
              </template>
            </el-table-column>
            <el-table-column label="商品名称">
              <template slot-scope="scope">
                {{ scope.row.goods_vo.name }}
              </template>
            </el-table-column>
            <el-table-column prop="product_vo.spec_name" label="规格型号">
              <!--  <template slot-scope="scope">
                {{ scope.row.product_vo.spec_name.join('/') }}
              </template> -->
            </el-table-column>
            <el-table-column label="单位">
              <template slot-scope="scope">
                {{ scope.row.product_vo.unit }}
              </template>
            </el-table-column>
            <el-table-column label="单价">
              <template slot-scope="scope">
                ¥{{ scope.row.product_vo.price }}
              </template>
            </el-table-column>
            <el-table-column label="购买数量">
              <template slot-scope="scope">
                <span v-if="id">{{ scope.row.num }}</span>
                <span v-else>{{ scope.row.order_num }}</span>
              </template>
            </el-table-column>
            <el-table-column label="退货数量">
              <template slot-scope="scope">
                <el-input maxlength="12" v-model="scope.row.return_num" @input="passInput(scope.row)"
                  :disabled="type === 'detail' || type === 'audit'" />
              </template>
            </el-table-column>
            <el-table-column prop="not_return_num" label="未退数量"></el-table-column>
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button size="mini" :disabled="type === 'detail' || type === 'audit'" type="danger"
                  @click="orderReturnAddForm.item_list.splice(scope.$index, 1)">删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
      </div>
    </el-form>
    <div class="footer">
      <!--  <el-button v-if="type === 'audit'" type="primary" @click="auditorderReturnForm('AuditPass')">审核通过
      </el-button>
      <el-button v-if="type === 'audit'" type="danger" @click="auditorderReturnForm('AuditReject')">审核驳回
      </el-button> -->
      <el-button v-if="type !== 'audit' && type !== 'detail'" type="primary" @click="submitorderReturnAddForm">保存
      </el-button>
      <el-button @click="roBack()">返回
      </el-button>
    </div>
  </div>
</template>

<script>
import { mapGetters } from 'vuex'
import * as API_Setting from '@/api/setting'
import * as API_BasicSetting from '@/api/basicSetting'
import * as API_orderReturn from '@/api/orderReturn'
import { Foundation } from '~/ui-utils'
import * as API_Auth from '@/api/auth'
export default {
  name: 'orderReturnAdd',
  data() {
    return {
      adminList: [],
      fileList: [],
      deptList: [],
      id: '',
      warehouseList: [],
      /** 商品列表 */
      goodsList: [],
      /** 供应商退货表单*/
      orderReturnAddForm: {
        order_id: '',
        item_list: [],
        return_time:'',
      },
      type: ''
    }
  },
  computed: {
    ...mapGetters(['user']),
    timeDefault() {
      var date = new Date();
      var s1 = date.getFullYear() + "-" + (date.getMonth() + 1) + "-" + (date.getDate()) + " " + date.getHours() + ':' + date.getMinutes() + ':' + date.getSeconds();
      return s1;
    },
  },
  mounted() {
    this.GET_DeptList()
    this.GET_AdministratorList()
  },
  watch: {
    $route: {
      immediate: true,
      handler(newVal) {
        if (this.$route.name === 'orderReturnAudit') {
          this.type = 'audit'
        } else if (this.$route.name === 'orderReturnAdd') {
          console.log(this.$route);
          this.orderReturnAddForm = {
            item_list: []
          }
          /*  this.orderReturnAddForm.handle_by_id = this.user.uid */
          /* this.orderReturnAddForm.dept_id = this.user.dept_id */
          this.GET_WarehouseList({ dept_id: this.user.dept_id })
          this.GET_ReturnDetails(this.$route.params.id)
          this.id = this.$route.params.id
          this.orderReturnAddForm.return_time=this.timeDefault
          /*  this.$set(this.orderReturnAddForm, 'return_time', new Date().getTime()) */
          this.type = 'add'
        } else if (this.$route.name === 'productClassCheck') {
          this.type = 'detail'
          this.id = this.$route.params.id
          this.orderReturnAddForm.id = this.$route.params.id
          this.GET_orderReturnDetail()
        }
        if (this.$route.params.id) {

        }
      }
    }
  },
  methods: {
    GET_ReturnDetails(id) {
      API_orderReturn.getWarehouseOutProduct(id).then(response => {
        this.orderReturnAddForm.sn = response.sn
        this.orderReturnAddForm.item_list = response.item_list
      })
    },
    /* 校验输入数量 */
    passInput(value) {
      if (value.num < value.return_num) {
        this.$message({
          message: "请重新输入退货数量",
          type: "error",
          showClose: true,
        });
        return;
      }
    },
    /** 获取人员列表 */
    GET_AdministratorList() {
      API_Auth.getAdministratorList({
        page_no: 1,
        page_size: 9999,
        user_state: 0
      }).then(response => {
        this.adminList = response.data
      })
    },
    /** 选择订单编号 */
    async handleSelectOrderSn() {
      const orders = await this.$EnPickerOrder({
        orderApi: '/admin/erp/order',
        selectedIds: [this.orderReturnAddForm.order_sn],
        /* orderApiParams: { ship_flag: true }, */
        limit: 1
      })
      this.orderReturnAddForm.order_id = orders[0].id
      if (orders) {
        API_orderReturn.getWarehouseOutProduct(orders[0].id).then(response => {
          /* const product_list =*/
          /* response.item_list.map(el => {
              el.allow_sn=el.goods_vo.allow_sn
              el.bar_code=el.goods_vo.bar_code
              el.brand_id=el.goods_vo.brand_id
              el.brand_name=el.goods_vo.brand_name
              el.category_id=el.goods_vo.category_id
              el.category_ids=el.goods_vo.category_ids
              el.category_name=el.goods_vo.category_name
              el.cost_price=el.goods_vo.cost_price
              el.create_time=el.goods_vo.create_time
              el.creator=el.goods_vo.creator
              el.description=el.goods_vo.description
              el.en_name=el.goods_vo.en_name
              el.freight_template_id=el.goods_vo.freight_template_id
              el.goods_style=el.goods_vo.goods_style
              el.goods_unit=el.goods_vo.goods_unit
              el.goods_unit=el.goods_vo.goods_unit
              el.have_spec=el.goods_vo.have_spec
              el.hire_or_sail=el.goods_vo.hire_or_sail
               el.id=el.goods_vo.id
              el.image=el.goods_vo.image
              el.image_list=el.goods_vo.image_list
              el.label_names=el.goods_vo.label_names
              el.market_enable=el.goods_vo.market_enable
              el.mkt_price=el.goods_vo.mkt_price
              el.name=el.goods_vo.name
              el.params_list=el.goods_vo.params_list
              el.price=el.goods_vo.price
              el.sn=el.goods_vo.sn
              el.sn_code=el.goods_vo.sn_code
              el.sort=el.goods_vo.sort
              el.update_time=el.goods_vo.update_time
              el.updater=el.goods_vo.updater
              el.usable_stock=el.goods_vo.usable_stock
              el.video=el.goods_vo.video
              return el
            })*/
          this.orderReturnAddForm.sn = response.sn
          this.orderReturnAddForm.item_list = response.item_list

        })
      }
    },
    changewarehouseList(e) {
      this.$set(this.orderReturnAddForm, 'warehouse_id', '')
      this.GET_WarehouseList({ dept_id: e })
    },
    /** 获取仓库 */
    GET_WarehouseList(e) {
      API_BasicSetting.getWarehouseListAll(e).then(response => {
        this.warehouseList = response
      })
    },
    auditorderReturnForm(status) {
      this.$confirm('确定吗？', '提示', { type: 'warning' }).then(() => {
        API_orderReturn.auditorderReturn(this.id, { status: status }).then(response => {
          this.$message.success('审核完成')
          const { callback } = this.$route.params
          if (typeof callback === 'function') callback()
          this.$store.dispatch('delCurrentViews', {
            view: this.$route,
            $router: this.$router
          })
          this.$router.push({ name: 'orderReturn' })
        })
      }).catch(() => { })
    },
    roBack() {
      const { callback } = this.$route.params
      if (typeof callback === 'function') callback()
      this.$store.dispatch('delCurrentViews', {
        view: this.$route,
        $router: this.$router
      })
      this.$router.push({ name: 'orderReturn' })
    },
    submitorderReturnAddForm() {
      const { id } = this.orderReturnAddForm
      const params = this.MixinClone(this.orderReturnAddForm)
      const mapList = {}
      let notRteurn=false
      params.order_id=this.id
      params.order_sn = params.sn
      params.item_list = params.item_list.map(el => {
        el.order_item_id = el.id
        el.order_num = el.num
        el.product_id = el.product_id
        el.return_num = el.return_num
        if(el.return_num>el.not_return_num){
          notRteurn=true
        }
        return el
      })
      if(notRteurn) return this.$message.error("退货数量大于未退数量!")
      if (id) {
        API_orderReturn.editorderReturn(id, params).then(response => {
          this.$message.success('修改成功！')
          const { callback } = this.$route.params
          if (typeof callback === 'function') callback()
          this.$store.dispatch('delCurrentViews', {
            view: this.$route,
            $router: this.$router
          })
          this.$router.push({ name: 'orderReturn' })
        })
      } else {
        API_orderReturn.addorderReturn(params).then(() => {
          this.$message.success('添加成功！')
          const { callback } = this.$route.params
          if (typeof callback === 'function') callback()
          this.$store.dispatch('delCurrentViews', {
            view: this.$route,
            $router: this.$router
          })
          this.$router.push({ name: 'orderReturn' })
        })
      }
    },
    /** 获取部门 */
    GET_DeptList() {
      API_Setting.getDeptList().then(response => {
        this.deptList = Foundation.buildTree(response, '0')
      })
    },
    GET_orderReturnDetail() {
      API_orderReturn.getorderReturnInfo(this.id).then(response => {
        /* response.item_list.map(el => {
            el.allow_sn=el.goods_vo.allow_sn
            el.bar_code=el.goods_vo.bar_code
            el.brand_id=el.goods_vo.brand_id
            el.brand_name=el.goods_vo.brand_name
            el.category_id=el.goods_vo.category_id
            el.category_ids=el.goods_vo.category_ids
            el.category_name=el.goods_vo.category_name
            el.cost_price=el.goods_vo.cost_price
            el.create_time=el.goods_vo.create_time
            el.creator=el.goods_vo.creator
            el.description=el.goods_vo.description
            el.en_name=el.goods_vo.en_name
            el.freight_template_id=el.goods_vo.freight_template_id
            el.goods_style=el.goods_vo.goods_style
            el.goods_unit=el.goods_vo.goods_unit
            el.goods_unit=el.goods_vo.goods_unit
            el.have_spec=el.goods_vo.have_spec
            el.hire_or_sail=el.goods_vo.hire_or_sail
            /* el.id=el.goods_vo.id
            el.image=el.goods_vo.image
            el.image_list=el.goods_vo.image_list
            el.label_names=el.goods_vo.label_names
            el.market_enable=el.goods_vo.market_enable
            el.mkt_price=el.goods_vo.mkt_price
            el.name=el.goods_vo.name
            el.params_list=el.goods_vo.params_list
            el.price=el.goods_vo.price
            el.sn=el.goods_vo.sn
            el.sn_code=el.goods_vo.sn_code
            el.sort=el.goods_vo.sort
            el.update_time=el.goods_vo.update_time
            el.updater=el.goods_vo.updater
            el.usable_stock=el.goods_vo.usable_stock
            el.video=el.goods_vo.video
            return el
          }) **/
          response.item_list.map(el=>{
            el.return_num=0
          })
        this.orderReturnAddForm = response
        this.GET_WarehouseList({ dept_id: response.dept_id })
      })
    }
  }
}
</script>

<style type="text/scss" lang="scss" scoped>
/** 底部步骤 */
.footer {
  width: 100%;
  padding: 10px;
  bottom: 0px;
  text-align: center;
  z-index: 999;
}

.mx {
  display: flex;
  align-items: center;

  .button {
    margin-left: 10px;
  }
}

.bg-in-stock {
  background-color: #fff;
  margin: 10px;
  padding: 25px;
}

.goods-info {
  display: flex;

  .goods-name-box {
    text-align: left;

    .goods-name {
      text-overflow: ellipsis;
      display: -webkit-box;
      -webkit-line-clamp: 2;
      -webkit-box-orient: vertical;
      overflow: hidden;
      line-height: 16px;
    }

    .specs {
      color: #999999;
    }
  }
}

/deep/ {
  .el-input--suffix .el-input__inner {
    padding-right: 10px;
  }

  .error-input {
    .el-input__inner {
      border: 1px solid red;
    }
  }
}

/deep/ .el-form-item {
  width: 100%;

  .el-form-item__content {
    width: 80%;
  }
}
</style>
