<template>
  <div v-loading="loading">
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="150px" class="order_form">
      <el-form-item label="订单编号" prop="F_OrderId">
        <el-input v-model="ruleForm.F_OrderId" disabled="false" />
      </el-form-item>
      <el-form-item label="售后类型" prop="F_Type">
        <el-select
          v-model="ruleForm.F_Type"
          class="form_select"
          filterable
          clearable
          placeholder="请选择售后类型"
        >
          <el-option label="调换货" value="1"></el-option>
          <el-option label="退货" value="2"></el-option>
          <el-option label="部分退货" value="3"></el-option>
          <el-option label="对发货" value="4"></el-option>
          <el-option label="补发货" value="5"></el-option>
          <el-option label="补差额" value="6"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="变动金额" prop="F_Money">
        <el-input v-model="ruleForm.F_Money" placeholder="-需要退 +用户需补" />
      </el-form-item>
      <el-form-item label="售后原因类型" prop="F_ReturnType">
        <el-select
          v-model="ruleForm.F_ReturnType"
          class="form_select"
          filterable
          clearable
          placeholder="请选择售后原因类型"
        >
          <el-option
            v-for="item in afterSaleReasonsList"
            :key="item.F_ValueId"
            :label="item.F_Value"
            :value="item.F_Value"
          ></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="售后原因" prop="F_ReturnDes">
        <el-input v-model="ruleForm.F_ReturnDes" placeholder="请输入售后原因" />
      </el-form-item>
      <el-form-item label="退回商品状态" prop="F_ProductStatus">
        <el-input v-model="ruleForm.F_ProductStatus" placeholder="请输入退回商品状态" />
      </el-form-item>
      <el-row>
        <el-col :span="8">
          <el-form-item label="商品分类" prop="parentids">
            <el-cascader
              v-model="parentids"
              :options="commodityTypeLists"
              :props="typeDropProps"
              placeholder="请选择商品分类"
              clearable
              filterable
              change-on-select
              @change="commodityTypeChange"
              style="width: 100%;"
            />
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品" prop="productName">
            <el-select
              v-model="commoditySearchData.productName"
              class="filter-item"
              value-key="F_ProductId"
              clearable
              placeholder="请选择商品"
              @change="commodityListChange"
            >
              <el-option
                v-for="item in commodityListLists"
                :key="item.F_ProductId"
                :label="item.F_ProductName"
                :value="item"
              ></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="商品数量" prop="num">
            <el-input-number v-model="commoditySearchData.num" :min="1" label="描述文字"></el-input-number>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-form-item>
          <el-button type="primary" @click="addCommodity">添加商品</el-button>
        </el-form-item>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="补发商品">
            <el-table :data="commodityTableData" stripe style="width: 100%">
              <el-table-column prop="F_ProductName" label="商品名称" align="center"></el-table-column>
              <el-table-column prop="F_Count" label="商品数量" align="center"></el-table-column>
              <el-table-column label="操作" align="center">
                <template slot-scope="scope">
                  <el-button type="text" @click="btn_deleteCommodity(scope.row)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="退回商品">
            <el-table
              :data="oldCommodityTableData"
              stripe
              style="width: 100%"
              @selection-change="handleSelectionChange"
              ref="oldCommodityTable"
            >
              <el-table-column type="selection" width="55"></el-table-column>
              <el-table-column prop="F_ProductName" label="商品名称" align="center"></el-table-column>
              <el-table-column prop="F_Count" label="商品数量" align="center"></el-table-column>
            </el-table>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="售后备注" prop="F_Remark">
        <el-input
          :autosize="{ minRows: 4}"
          v-model="ruleForm.F_Remark"
          type="textarea"
          placeholder="请输入售后备注"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submitForm(0)">保存</el-button>
        <el-button type="primary" @click="submitForm(1)">提交</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { getDictionaryValueList } from '@/api/commonAPI'
import { getOrder } from '@/api/orderManagement/orderList'
import { getCommodityType } from '@/api/commodityManagement/commodityType'
import { getCommodityList } from '@/api/commodityManagement/commodityList'
import { addAfterSaleList, getAfterSaleList, getAfterSaleOrderCommodityList } from "@/api/afterSaleManagement/afterSaleList";

export default {
  name: "AfterSale",
  props: {
    rowid: {
      type: String,
      default: ""
    },
    collectionAfterSalesReasonType: {
      type: String,
      default: ""
    },
    layerid: {
      type: String,
      default: ""
    }
  },
  data () {
    return {
      parentids: [],
      afterSaleReasonsList: [], //售后原因类型
      commodityListLists: [],
      commodityTypeLists: [], //商品分类下拉数据
      // 自定义菜单下拉数据的key值
      typeDropProps: {
        value: 'id',
        label: 'text'
      },
      commodityTableData: [], //添加商品
      commoditySearchData: { //商品搜索数据
        classId: '', // 商品分类id
        className: '', // 商品分类名称
        productName: '', //商品名称
        productId: '', //商品id
        num: 1, //商品数量
      },
      oldCommodityTableData: [], //退回商品列表
      oldDetailListSelection: [], // 退回商品选中数据
      ruleForm: {
        F_OrderId: '', //订单编号
        F_DetailList: '', //补发产品列表
        F_OldDetailList: '', //退回产品列表
        F_Type: '', //合并类型
        F_Money: '', //减免金额
        F_Remark: '', //销售备注
        F_ReturnType: '', //售后原因类型
        F_ReturnDes: '', //售后原因
        F_ProductStatus: '', //退回商品状态
        F_CheckStateSH: '', //0保存 1提交按钮 2不通过
      },
      rules: {
        order1: [{
          required: true,
          trigger: 'blur',
          message: '请输入订单编号1',
        }],
        order2: [{
          required: true,
          trigger: 'blur',
          message: '请输入订单编号2',
        }],
        F_Type: [{
          required: true,
          trigger: 'change',
          message: '请选择售后类型',
        }],
        F_Money: [{
          required: true,
          trigger: 'blur',
          message: '请输入变动金额',
        }],
        F_ReturnType: [{
          required: true,
          trigger: 'change',
          message: '请选择售后原因类型',
        }],
        F_ReturnDes: [{
          required: true,
          trigger: 'blur',
          message: '请输入售后原因',
        }],
        F_ProductStatus: [{
          required: true,
          trigger: 'blur',
          message: '请输入退回商品状态',
        }],
      },
      loading: false
    };
  },
  created () {
    this.getCommodityTypeSelect()
    this.getAfterSaleReasons()
    Promise.all([
    ]).then(() => {
      if (this.rowid) {
        this.ruleForm.F_OrderId = this.rowid
        this.getAfterSaleOrderCommodity(this.rowid)
      }
      if (this.collectionAfterSalesReasonType) {
        this.ruleForm.F_ReturnType = this.collectionAfterSalesReasonType
      }
    });
  },
  methods: {
    submitForm (state) {
      this.$refs.ruleForm.validate(valid => {
        if (valid) {
          this.loading = true;
          this.ruleForm.F_CheckStateSH = state
          //添加
          addAfterSaleList(this.ruleForm).then(response => {
            this.loading = false
            if (response.state.toLowerCase() === 'success') {
              this.$parent.$layer.close(this.layerid)
              this.$parent.getList() // 重新加载父级数据
              this.$message.success('恭喜你，添加成功!')
            }
          }).catch(() => {
            this.loading = false
          })
          return
        } else {
          this.$message.error("请输入有效的必填项信息!");
          return false;
        }
      });
    },
    //获取商品分类
    getCommodityTypeSelect () {
      this.loading = true
      return new Promise(resolve => {
        const data = {
          pageindex: 1, // int 第几页
          pagesize: 300, // int 每页几条信息
          ParentId: 0,
        }
        getCommodityType(data).then(response => {
          this.loading = false
          if (response.state.toLowerCase() === 'success') {
            this.commodityTypeLists = response.data
          }
        })
        resolve()
      })
    },

    commodityTypeChange (item) {
      this.commoditySearchData.classId = this.parentids[this.parentids.length - 1]
      this.getCommodityListSelect()
    },
    commodityListChange (item) {
      this.commoditySearchData.productId = item.F_ProductId
      this.commoditySearchData.productName = item.F_ProductName
    },
    //获取商品
    getCommodityListSelect () {
      this.loading = true
      return new Promise(resolve => {
        const params = {
          pageindex: 1, // int 第几页,
          pagesize: 300, // int 每页几条信息,
          ProductId: '',
          ClassId: this.commoditySearchData.classId === '' ? 0 : this.commoditySearchData.classId,
          ClassName: '',
          ProductName: '',
          PinyinShort: '',
          ProductNumber: '',
          ProductShortName: '',
          tag: '',
          issale: 1,
        }
        getCommodityList(params).then(response => {
          this.loading = false
          if (response.state.toLowerCase() === 'success') {
            this.commodityListLists = response.data.Rows
          }
        })
        resolve()
      })
    },
    addCommodity () {
      if (this.commoditySearchData.productName === '') {
        this.$message({
          message: '请选择商品！',
          type: 'warning'
        })
        return
      }
      if (this.commodityTableData.length > 0) {
        for (let i = 0; i < this.commodityTableData.length; i++) {
          if (this.commodityTableData[i].F_ProductId === this.commoditySearchData.productId) {
            this.commodityTableData[i].F_Count = this.commodityTableData[i].F_Count + this.commoditySearchData.num
            return
          }
        }
      }
      let data = {
        F_ProductId: this.commoditySearchData.productId,
        F_ProductName: this.commoditySearchData.productName,
        F_Count: this.commoditySearchData.num,
      }
      this.commodityTableData.push(data)
      let idsQuantity = []
      for (let i = 0; i < this.commodityTableData.length; i++) {
        idsQuantity.push(this.commodityTableData[i].F_ProductId + ',' + this.commodityTableData[i].F_Count)
      }
      this.ruleForm.F_DetailList = idsQuantity.join('|') //补发产品列表
    },
    //删除商品
    btn_deleteCommodity (val) {
      let index = this.commodityTableData.indexOf(val)
      this.commodityTableData.splice(index, 1)
    },
    // 售后订单商品列表
    getAfterSaleOrderCommodity (rid) {
      const params = {
        orderid: rid
      }
      getAfterSaleOrderCommodityList(params).then(response => {
        if (response.state.toLowerCase() === 'success') {
          const res = response.data
          this.oldCommodityTableData = res
          this.$nextTick(() => {
            this.oldCommodityTableData.forEach((row, index) => {
              this.$refs.oldCommodityTable.toggleRowSelection(row)
            })
          }, 1)
        }
      })
    },
    //售后原因类型
    getAfterSaleReasons () {
      return new Promise(resolve => {
        const params = {
          isleaf: true,
          code: 'AfterSaleReasons'
        }
        getDictionaryValueList(params).then(response => {
          if (response.state.toLowerCase() === 'success') {
            this.afterSaleReasonsList = response.data.Rows
          }
        })
      })
    },
    //选择多个
    handleSelectionChange (selection) {
      let idsQuantity = []
      this.oldDetailListSelection = selection
      for (let i = 0; i < this.oldDetailListSelection.length; i++) {
        idsQuantity.push(this.oldDetailListSelection[i].F_ProductId + ',' + this.oldDetailListSelection[i].F_Count)
      }
      this.ruleForm.F_OldDetailList = idsQuantity.join('|')
    },
  }
};
</script>

<style rel="stylesheet/scss" lang="scss">
.order_form .form_select {
  width: 100%;
}
</style>
