<template>
  <div class="xd-customer-operation">
    <div class="xd-customer-operation__btn">
      <el-button type="primary" :size="btn_size" @click="handleOpen">{{btn_name}}</el-button>
    </div>
    <xd-dialog
      :title="title"
      v-if="dialogVisible"
      :show.sync="dialogVisible"
      :width="dialog_width"
      @onConfirm="handleDialogConfirm"
      @onClose="handleDialogClear"
      @onCancel="handleDialogClear"
    >
      <div class="xd-customer-operation__dialog">
        <div class="xd-customer-operation__dialog-operation">
          <div class="xd-customer-operation__dialog-operation-item">
            <div>处理方式：</div>
            <div class="input60">
              <xd-select-list
                :list="operationList"
                v-model="form.operation"
                @change="handleOperation"
              ></xd-select-list>
            </div>
          </div>
          <div class="xd-customer-operation__dialog-operation-item">
            <div>售后类型：</div>
            <div class="input60">
              <xd-select-list :list="typeList" v-model="form.type"></xd-select-list>
            </div>
          </div>
          <div class="xd-customer-operation__dialog-operation-item" v-if="$setting.system!=='supplier'">
            <div>审核人员：</div>
            <div class="input60">
              <xd-select-list :list="userCheckList" v-model="form.user_check"></xd-select-list>
            </div>
          </div>
        </div>
        <div class="xd-customer-operation__dialog-title" v-if="form.operation">
          <div>{{fromTitle}}</div>
          <div v-if="price">
            <span>总价：</span>
            <xd-table-price :price="price" :key="priceRefresh"></xd-table-price>
          </div>
        </div>
        <div class="xd-customer-operation__dialog-table" v-if="form.operation">
          <div class="product_base" v-if="form.operation === 'refund_and_good'">
            <div class="product_base_item" v-if="base_info"><span>运费:</span><span style="color:red">{{base_info.freight_price==0?0:$xdHelper.divisionFloatNumber(base_info.freight_price,100)}}</span>元</div>
          </div>
          <xd-table
            ref="table"
            is-border
            :list="tableList"
            :selection-key="selectionKey"
            :headers="headers"
            :key="tableRefresh"
            :default-select="form.selectTableListIds"
            :selectionRowIsDisabled="item=>handleSelectionRowIsDisabled(item,form.operation)"
            @onSelect="handleTableSelect"
            @change="handleTableChange"
            @onEdit="handleTableEdit"
          >
            <template slot="info" slot-scope="scope">
              <xd-store-product
                :key="tableRefresh"
                :list="getProductInfo(scope.row)"
                width="60"
                height="60"
              ></xd-store-product>
            </template>
            <template slot="send" slot-scope="scope" v-if="base_info && form.operation === 'refund_and_good'">
              <!-- 核销门店 -->
              <div v-if="scope.row.db_from==='offline'">核销门店:{{scope.row.shop_name}}</div>
              <!-- 快递配送 -->
              <div v-if="scope.row.delivery_method==='logistics'">配送方式:{{scope.row.delivery_method_name}}</div>
              <div v-if="scope.row.delivery_method==='logistics'">收货人:{{base_info.receipt_username}}</div>
              <div v-if="scope.row.delivery_method==='logistics'">收货人手机号:{{base_info.receipt_phone_number}}</div>
              <div v-if="scope.row.delivery_method==='logistics'">收货地址:{{base_info.receipt_address}}</div>
              <!-- 自提 -->
              <div v-if="scope.row.delivery_method==='takeout'">配送方式:{{scope.row.delivery_method_name}}</div>
              <div v-if="scope.row.delivery_method==='takeout'">自提门店:{{scope.row.subscribe_info.shop_name}}</div>
              <div v-if="scope.row.delivery_method==='takeout'">自提时间:{{scope.row.subscribe_info.subscribe_time_info}}</div>
              <!-- 同城配送 -->
              <div v-if="scope.row.delivery_method==='samecity'">配送方式:{{scope.row.delivery_method_name}}</div>
              <!-- <div v-if="scope.row.delivery_method==='samecity'">配送门店:{{scope.row.subscribe_info.shop_name}}</div>
              <div v-if="scope.row.delivery_method==='samecity'">配送时间:{{scope.row.subscribe_info.subscribe_time_info}}</div> -->
              <div v-if="scope.row.delivery_method==='samecity'">收货人:{{base_info.receipt_username}}</div>
              <div v-if="scope.row.delivery_method==='samecity'">收货人手机号:{{base_info.receipt_phone_number}}</div>
              <div v-if="scope.row.delivery_method==='samecity'">收货地址:{{base_info.receipt_address}}</div>
            </template>
            <template slot="can_use_sale_price" slot-scope="scope">
              <div><span class="red">{{$xdHelper.divisionFloatNumber(scope.row.can_use_sale_price, 100)}}</span>元</div>
              <div v-if="form.operation === 'refund_and_good'&&scope.row.user_server_amount">(含平台服务费<span class="red">{{$xdHelper.divisionFloatNumber(scope.row.user_server_amount,100)}}</span>元)</div>
              <div>
                <el-button style="margin:auto" type="primary" size="small" @click="lookDetailed(scope.row)">查看支付明细</el-button>
              </div>
            </template>
            <template slot="refund_sale_price_edit" slot-scope="scope">
              <div style="display: flex; flex-direction: column; align-items: center; justify-content: center;">
                <xd-table-edit-item
                  type="text"
                  :blur="true"
                  :key="tableRefresh"
                  align="center"
                  v-model="scope.row.refund_sale_price"
                  @onSave="(cb)=>{handleRefundSalePriceSave(scope.row, cb, true)}"
                ></xd-table-edit-item>
                <el-button
                  v-if="scope.row.is_edit_refund_sale_price==='Y'&&scope.row.is_edit_refund_purchase_price==='Y'"
                  size="mini"
                  type="text"
                  style="margin-left: 5px;"
                  @click="handleAutoCalcRefundSalePrice(scope.row)"
                >自动计算</el-button>
              </div>
            </template>
            <template slot="refund_purchase_price_edit" slot-scope="scope">
              <div style="display: flex; flex-direction: column; align-items: center; justify-content: center;">
                <xd-table-edit-item
                  type="text"
                  :blur="true"
                  :key="tableRefresh"
                  align="center"
                  v-model="scope.row.refund_purchase_price"
                  @onSave="(cb)=>{handleRefundPurchasePriceSave(scope.row, cb, true)}"
                ></xd-table-edit-item>
                <el-button
                  v-if="scope.row.is_edit_refund_sale_price==='Y'&&scope.row.is_edit_refund_purchase_price==='Y'"
                  size="mini"
                  type="text"
                  style="margin-left: 5px;"
                  @click="handleAutoCalcRefundPurchasePrice(scope.row)"
                >自动计算</el-button>
              </div>
            </template>
          </xd-table>
        </div>
        <div class="xd-customer-operation__dialog-change" v-if="form.operation === 'zero'">
          <div class="xd-customer-operation__dialog-change-search">
            <div class="xd-customer-operation__dialog-change-search-title">选择换货商品</div>
            <div class="xd-customer-operation__dialog-change-search-select">
              <div>供货商选择：</div>
              <div class="xd-customer-operation__dialog-change-search-select-chose">
                <!-- <xd-cascade-select
                  v-model="product.changeInfo"
                  @loadChildren="handleChildren"
                  :disabled="false"
                  :multiple="false"
                ></xd-cascade-select>-->
                <xd-remote-input
                  placeholder="请选择供应商"
                  width="30%"
                  :multiple="false"
                  :remote-search="remoteSearch"
                  v-model="product.supplier_id"
                  @change="supplierChange"
                ></xd-remote-input>
                <!-- <xd-select-list
                  v-if="product.supplier_id.length>0"
                  :list="productList"
                  v-model="product.product_id"
                  class="input20"
                  placeholder="请选择商品"
                  @change="productChange"
                ></xd-select-list> -->
                <xd-remote-input
                  v-if="product.supplier_id.length>0"
                  placeholder="请选择商品"
                  width="30%"
                  :multiple="false"
                  :remote-search="remoteSearchProduct"
                  v-model="product.product_id"
                  @change="productChange"
                ></xd-remote-input>
                <xd-select-list
                  v-if="product.product_id&&skuList.length>0"
                  :list="skuList"
                  v-model="product.sku_id"
                  class="input20"
                  placeholder="请选择sku"
                ></xd-select-list>
                <el-input
                  class="input20"
                  type="text"
                  autosize
                  placeholder="请输入数量"
                  v-model="product.num"
                ></el-input>
                <!-- <xd-select-list
                  :list="expressList"
                  v-model="product.express_id"
                  class="input20"
                  placeholder="请选择物流"
                ></xd-select-list> -->
                <el-button
                  style="margin-left: 10px"
                  size="small"
                  type="primary"
                  @click="handleAddChange(product)"
                >添加</el-button>
              </div>
            </div>
          </div>
          <div class="xd-customer-operation__dialog-change-title">
            <div>已选换购商品</div>
            <div v-if="price">
              <span>总价：</span>
              <xd-table-price :price="price" :key="priceRefresh"></xd-table-price>
            </div>
          </div>
          <div class="xd-customer-operation__dialog-change-table">
            <xd-table
              ref="tableChange"
              is-border
              :list="changeTableList"
              :selection-key="selectionKey"
              :headers="changeHeaders"
              :key="changeTableRefresh"
              @onClick="handleTableClick"
            >
              <template slot="info" slot-scope="scope">
                <xd-store-product
                  :key="changeTableRefresh"
                  :list="getProductInfo(scope.row)"
                  width="60"
                  height="60"
                ></xd-store-product>
              </template>
            </xd-table>
          </div>
        </div>
        <div
          class="xd-customer-operation__dialog-options"
          v-if="form.operation"
          :style="{
						marginTop: (form.operation === 'refund' || form.operation === 'refund_and_good') ? 0 : '10px'
					}"
        >
          <template v-if="form.operation === 'refund' || form.operation === 'refund_and_good'">
            <div>
              <div>退款渠道：</div>
              <div>
                <xd-radio-list
                  :list="refundList"
                  v-model="form.refund_channel"
                  :default-value="form.refund_channel"
                ></xd-radio-list>
              </div>
            </div>
            <div v-if="form.refund_channel==='wallet'">
              <div></div>
              <div>
                <xd-select-list
                :list="walletListForSelect"
                v-model="form.front_select_unique_key"
                class="input20"
                placeholder="请选择钱包"
              ></xd-select-list>
              </div>
            </div>
            <div v-if="setting.db_from==='online'">
              <div>是否退运费：</div>
              <div>
                <xd-radio-list
                  :list="isRefundFreightList"
                  v-model="form.is_refund_freight_price"
                  :default-value="form.is_refund_freight_price"
                ></xd-radio-list>
              </div>
            </div>
            <!-- <div v-if="form.is_refund_freight_price === 'Y'">
              <div></div>
              <div>
                <el-input
                  class="input20"
                  type="text"
                  autosize
                  :disabled="!setting.sub_order_id"
                  placeholder="请输入运费"
                  v-model="form.refund_freight_price"
                ></el-input>
                <span style="margin-left: 5px">元</span>
              </div>
            </div> -->

          </template>
          <div v-if="form.operation === 'zero' || form.operation === 'exchange'">
            <div>换货备注：</div>
            <div>
              <el-input
                class="input70"
                type="textarea"
                autosize
                placeholder="请输入换货备注"
                v-model="form.description"
                :autosize="{ minRows: 2, maxRows: 4}"
              ></el-input>
            </div>
          </div>
          <div v-if="form.operation === 'exchange' || form.operation === 'again'" style="margin-top: 10px;">
            <div>快递公司：</div>
            <div class="express">
              <xd-select-list :list="expressList" v-model="form.express_id" class="input20"></xd-select-list>
              <el-input
                class="input50"
                type="text"
                autosize
                placeholder="请输入快递单号"
                v-model="form.express_num"
              ></el-input>
            </div>
          </div>
        </div>
        <div v-if="$setting.system==='admin'" class="xd-customer-operation__dialog-operation-item" style="margin-top: 10px;">
            <div>供货商扣分：</div>
            <div>
              <div v-for="(item,index) in setting.scoringData" :key="index" class="score_box">
                <el-select v-model="setting.scoringData[index]['supplier_id']" clearable placeholder="请选择">
                  <el-option
                    v-for="item in setting.supplierList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
                <el-select v-model="setting.scoringData[index]['score']" clearable placeholder="请选择">
                  <el-option
                    v-for="item in setting.scoreList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
                <i v-if="(index + 1) === setting.scoringData.length" class="el-icon-circle-plus pl5" @click="add(item)" ></i>
                <i v-if="setting.scoringData.length > 1" class="el-icon-remove pl5" @click="remove(index)"></i>
              </div>
            </div>
          </div>
          <div v-if="form.operation === 'exchange' || form.operation === 'zero'|| form.operation === 'refund_and_good'" class="xd-customer-operation__dialog-operation-item">
            <div>回寄地址：</div>
            <!-- <div class="input60"> -->
              <el-input
                class="input60"
                type="textarea"
                autosize
                placeholder="请输入回寄地址"
                v-model="form.return_address"
                :autosize="{ minRows: 2, maxRows: 4}"
              ></el-input>
            <!-- </div> -->
          </div>
        <template slot="btn">
          <el-button size="medium" @click="handleDialogClear">取 消</el-button>
          <el-button size="medium" type="primary" @click="handleDialogConfirm">确 定</el-button>
        </template>
      </div>
    </xd-dialog>
  </div>
</template>

<script>
import emitter from 'element-ui/src/mixins/emitter'
import XdDialog from "@/components/XdDialog"
import XdSelectList from "@/components/XdSelectList"
import XdTablePrice from "@/components/XdTablePrice"
import XdRadioList from "@/components/XdRadioList"
import XdTable from "@/components/XdTable"
import XdTableEditItem from "@/components/XdTableEditItem"
import XdStoreProduct from "@/components/XdStoreProduct"
import XdCascadeSelect from "@/components/XdCascadeSelect"
import XdRemoteInput from "@/components/XdRemoteInput"
import { getConstantKeyForList } from "@/utils/constant"


export default {
  name: "XdCustomerOperation",
  components: {
    XdRadioList,
    XdTablePrice,
    XdSelectList,
    XdDialog,
    XdTable,
    XdTableEditItem,
    XdStoreProduct,
    XdCascadeSelect,
    XdRemoteInput
  },
  mixins: [emitter],
  props: {
    defaultValue: {
      type: Object | null,
      default: null,
    },

    maps: {
      type: Object | null,
      default () {
        return null
      },
    },

    setting: {
      type: Object,
      default () {
        return {}
      },
    },

    disabled: {
      type: Boolean,
      default: false,
    },

    size: {
      type: String,
      default: 'medium', //medium / small / mini
    },

    //自定义方法
    handleCustom: {
      type: Function || null,
      default: null
    },
    remoteSearch: {
      type: Function || null,
      default: null
    },
    remoteSearchProduct: {
      type: Function || null,
      default: null
    },
    supplierChange: {
      type: Function || null,
      default: null
    },
    productChange: {
      type: Function || null,
      default: null
    },
  },
  computed: {
    price () {
      if (this.operation === 'zero' || this.operation === 'exchange') {
        this.priceRefresh = Date.now()
        let price = 0
        this.selectTableList.map(item => {
          price = this.$xdHelper.addFloatNumber(price, this.handleCustom({ action: 'addPrice', data: item }))
        })
        return price
      }
      return null
    },
    /** 钱包选择列表：将 front_select_unique_key 映射为 value */
    walletListForSelect () {
      if (!this.walletList || this.$xdHelper.checkVarType(this.walletList) !== 'array') return []
      return this.walletList.map(item => ({
        ...item,
        value: item.front_select_unique_key,
      }))
    },
  },

  data () {
    return {
      selectionKey: 'id',
      btn_name: '操作',
      btn_size: 'mini',
      dialog_width: '1000px',
      defaultTitle: '工单处理',
      priceRefresh: 'priceRefresh',

      //0元购
      product: {
        changeInfo: null,//选中商品信息
        supplier_id: '',//供应商id
        product_id: '',//商品id
        sku_id: '',//skuid
        num: null, //商品件件数
        expressId: '',//选中快递ID
      },


      //处理方式
      operationList: [],

      //售后类型
      typeList: [],

      //审核人员
      userCheckList: [],

      //refund
      refundList: [],
      //钱包list
      walletList:[],
      //快递列表
      expressList: [],

      isRefundFreightList: getConstantKeyForList('IS'),


      //需要替换的商品table
      tableList: [],
      headers: [],
      tableRefresh: 'tableRefresh',
      //用来替换的商品table
      changeTableList: [],
      changeHeaders: [],
      changeTableRefresh: 'changeTableRefresh',

      //dialog
      dialogVisible: false,
      title: '',
      fromTitle: '',

      //form
      form: {
        operation: '', //处理方式
        type: '', //售后类型
        user_check: '', //审核人员
        description: '', //备注
        refund_channel: 'origin', //退款渠道
        express_id: '', //快递id
        express_num: '', //快递单号
        return_address:'',//   退回地址
        selectTableList: [], //选中更换的商品对象
        selectTableListIds: [], //选中更换的商品对象ID
        is_refund_freight_price: '', //是否退运费
        refund_freight_price: '',
        changeTableList: [], //用于替换的商品对象
        changeTableListIds: [], //用于替换的商品对象ID
        wallet_type:'',
        front_select_unique_key:'',
        supplier_scoring:[],
      },

      //map默认值
      defaultMap: {
        operation: 'operation',
        type: 'type',
        user_check: 'user_check',
        description: 'description',
        refund_channel: 'refund_channel',
        express_id: 'express_id',
        express_num: 'express_num',
        return_address:'return_address',
        selectTableList: 'selectTableList',
        selectTableListIds: 'selectTableListIds',
        refund_price: 'refund_price',
        again_count: 'again_count',
        is_refund_freight_price: 'is_refund_freight_price',
        refund_freight_price: 'refund_freight_price',
        wallet_type:'wallet_type',
        custom_wallet_id:'custom_wallet_id',
        supplier_scoring:'supplier_scoring',
      },
      productList: [],
      skuList: [],
      base_info:null,

    }
  },
  watch: {
    setting: {
      handler (n, o) {
        console.log("watch setting", n, o)
        this.changeTableList = n.changeTableList
        this.productList = n.productList
        this.skuList = n.skuList
        if(!this.skuList.length){
          this.$set(this.product, 'sku_id', '')
        }
        this.base_info = n.base_info
        console.log(n,this.base_info,n.base_info,n.skuList,n.productList,'this.base_info')
      },
      deep: true
    }
  },

  created () {
    console.log(this.setting,'this.setting')
    if (typeof this.handleCustom !== 'function') {
      throw new Error(`this.handleCustom()自定义访问未定义`)
    }

    //设置选项卡列表
    this.setSettingAndList()

    // this.handleOpen();
  },

  methods: {
    handleChildren ({ level, select, item }, resolve) {
      this.handleCustom({
        action: 'getProductInfo',
        data: { level, select, item, resolve }
      })
    },
    getProductInfo (row) {
      return this.handleCustom({ action: 'productInfo', data: row })
    },
    /**
     * @description 获取Maps中键与值
     * @param type {boolean} 返回值类型  true=>获取键  false=>值
     * @param keyword {string} 查找关键字
     * @return {null|string} null=>未找到  string=>找到
     */
    getMap (keyword, type) {
      let maps = null
      let value = null
      if (this.maps !== null && !this.$xdHelper.isEmpty(this.maps)) {
        maps = this.$xdHelper.cloneDeep(this.maps)
      }

      //先默认maps关系中找
      Object.keys(this.defaultMap).map(ky => {
        //获取键
        if (type) {
          if (this.defaultMap[ky] === keyword) {
            value = ky
          }
        } else {
          if (this.defaultMap[keyword]) value = this.defaultMap[keyword]
        }
      })

      //无外部map关系并且在默认关系表中无键
      if (value === null && maps === null) {
        return null
      }

      //无外部map关系并且在默认关系表中键
      if (value !== null && maps === null) {
        return value
      }

      //有外部map关系进行查找
      Object.keys(maps).map(ky => {
        //获取键
        if (type) {
          if (maps[ky] === keyword) {
            value = ky
          }
        } else {
          if (this.maps[keyword]) value = this.maps[keyword]
        }
      })
      return value

    },

    /**
     * @description 设置选项卡列表
     */
    setSettingAndList () {

      if (this.setting.selectionKey && this.$xdHelper.checkVarType(this.setting.selectionKey) === 'string') {
        this.selectionKey = this.setting.selectionKey
      }
      if (this.setting.btn_name && this.$xdHelper.checkVarType(this.setting.btn_name) === 'string') {
        this.btn_name = this.setting.btn_name
      }
      if (this.setting.btn_size && this.$xdHelper.checkVarType(this.setting.btn_size) === 'string') {
        this.btn_size = this.setting.btn_size
      }
      if (this.setting['default_title'] && this.$xdHelper.checkVarType(this.setting['default_title']) === 'string') {
        this.defaultTitle = this.setting['default_title']
      }
      if (this.setting.dialog_width && this.$xdHelper.checkVarType(this.setting.dialog_width) === 'string') {
        this.dialog_width = this.setting.dialog_width
      }

      if (this.setting.tableList && this.$xdHelper.checkVarType(this.setting.tableList) === 'array') {
        this.tableList = this.setting.tableList
        // 备份退款金额数据到每个 item 中
        this.tableList.forEach(item => {
          item._backup_refund_sale_price = item.refund_sale_price
          item._backup_refund_purchase_price = item.refund_purchase_price
        })
      }
      if (this.setting.changeTableList && this.$xdHelper.checkVarType(this.setting.changeTableList) === 'array') {
        this.changeTableList = this.setting.changeTableList
      }
      if (this.setting.operationList && this.$xdHelper.checkVarType(this.setting.operationList) === 'array') {
        this.operationList = this.setting.operationList
      }
      if (this.setting.typeList && this.$xdHelper.checkVarType(this.setting.typeList) === 'array') {
        this.typeList = this.setting.typeList
      }
      if (this.setting.userCheckList && this.$xdHelper.checkVarType(this.setting.userCheckList) === 'array') {
        this.userCheckList = this.setting.userCheckList
      }
      if (this.setting.refundList && this.$xdHelper.checkVarType(this.setting.refundList) === 'array') {
        this.refundList = this.setting.refundList
      }
      if (this.setting.walletList && this.$xdHelper.checkVarType(this.setting.walletList) === 'array') {
        this.walletList = this.setting.walletList.map(item => {
          const parsed = { ...item }
          if (item.param) {
            try {
              const param = JSON.parse(item.param)
              parsed.custom_wallet_id = param.custom_wallet_id
              parsed.front_select_unique_key = param.front_select_unique_key
            } catch (e) {
              console.warn('[XdCustomerOperation] 解析 wallet param 失败:', e, item.param)
            }
          }
          return parsed
        })
      }
      if (this.setting.expressList && this.$xdHelper.checkVarType(this.setting.expressList) === 'array') {
        this.expressList = this.setting.expressList
      }
      if (this.setting.productList && this.$xdHelper.checkVarType(this.setting.productList) === 'array') {
        this.productList = this.setting.productList
      }
      if (this.setting.skuList && this.$xdHelper.checkVarType(this.setting.skuList) === 'array') {
        this.skuList = this.setting.skuList
      }
      if (this.setting.base_info && this.$xdHelper.checkVarType(this.setting.base_info) === 'object') {
        this.base_info = this.setting.base_info
      }
    },

    /**
     * @description 设置选项卡列表
     */
    handleTableSelect ({ select, ids }) {
      console.log(select, ids,'this.$')
      let table = this.$xdHelper.cloneDeep(select)
      this.$set(this.form, 'selectTableList', table.map(item => {
        if (this.form.operation === 'refund' || this.form.operation === 'refund_and_good') {
          let refund_price = !item.refund_price ?
            null : this.$xdHelper.multiplyFloatNumber(Number(item.refund_price), 100)
          let refund_price_key = this.getMap('refund_price', false)
          item[refund_price_key] = refund_price
          delete item['refund_price']
        }
        if (this.form.operation === 'again') {
          item[this.getMap('again_count', false)] = item.again_count ? Number(item.again_count) : null
        }
        return item
      }))
      this.$set(this.form, 'selectTableListIds', table.map(item => {
        return item[this.selectionKey]
      }))
    },
    /**table改变**/
    handleTableChange({ value, data }){
      if(this.form.selectTableList&&this.form.selectTableList.length>0){
        this.form.selectTableList.map((item,index) => {
          if(item.product_id===data.product_id&&item.sku_id===data.sku_id){
            item.again_count = Number(data.again_count)
          }
         })
      }
    },
    //dialog==================
    handleOperation (value) {
      if (value.value === '') return
      this.title = `${this.defaultTitle} - ${value.select.label}`
      this.fromTitle = `${value.select.label}申请`
      let headers = []
      let changeHeaders = []
      //退款+供应商
      if (value.value === 'refund_and_good') {
        let baseHeaders = this.handleCustom({ action: 'headers', data: 'refund' })
        headers = this.$xdHelper.cloneDeep(baseHeaders)
        if(this.setting.settings.system==='admin'){
          headers.push(
            {type: 'normal', prop: 'supplier_name', align: 'center', minWidth: 150, label: '供应商'},
          )
        }
        headers.push(
          {type: 'normal', prop: 'send', align: 'left', minWidth: 150, label: '配送信息'},
        )
      }
      //退货退款
      else if (value.value === 'refund') {
        headers = this.handleCustom({ action: 'headers', data: 'refund' })
      }
      //换货 or 0元换购
      else if (value.value === 'exchange' || value.value === 'zero') {
        headers = this.handleCustom({ action: 'headers', data: 'change' })
        changeHeaders = this.handleCustom({ action: 'headers', data: 'exchange' })
      }
      //补发
      else {
        headers = this.handleCustom({ action: 'headers', data: 'again' })
      }

      // headers.splice(1, 0, { type: 'normal', prop: 'info', align: 'center', minWidth: 300, label: '商品信息' })
      // changeHeaders.splice(0, 0, { type: 'normal', prop: 'info', align: 'center', minWidth: 300, label: '商品信息' })
      this.headers = headers
      this.changeHeaders = changeHeaders
      console.log(value,headers,'dddd')
      this.$set(this.form, 'selectTableList', [])
      this.$set(this.form, 'selectTableListIds', [])
      this.tableRefresh = Date.now()
      this.changeTableRefresh = Date.now()

    },
    handleOpen () {
      if(this.setting.is_show_report==='Y'){
        this.$message.error(this.setting.pop_msg||'此订单含有他人货源商品，请上报平台创建售后单。')
        return
      }
      this.form = {
        operation: '', //处理方式
        type: '', //售后类型
        user_check: '', //审核人员
        description: '', //备注
        refund_channel: 'origin', //退款渠道
        express_id: '', //快递id
        express_num: '', //快递单号
        return_address:'',//回寄地址
        selectTableList: [], //选中更换的商品对象
        selectTableListIds: [], //选中更换的商品对象ID
        is_refund_freight_price: '',//是否退运费
        refund_freight_price: 0,//退运费金额默认为0
        changeTableList: [], //用于替换的商品对象
        changeTableListIds: [], //用于替换的商品对象ID
        wallet_type:'',
        front_select_unique_key:'',
      }
      this.dialogVisible = true
      this.title = this.defaultTitle
    },
    handleDialogConfirm () {
      if (this.form.operation === 'zero') {
        let tableChange = this.$xdHelper.cloneDeep(this.$refs['tableChange'].getTableData())
        this.$set(this.form, 'changeTableList', tableChange)
      }
      let temp = {}
      let form = this.$xdHelper.cloneDeep(this.form)
      //退款 or 退货退款
      if (this.form.operation === 'refund' || this.form.operation === 'refund_and_good') {
        delete form['description']
        delete form['express_id']
        delete form['express_num']
      }
      //换货 or 0元换购
      if (this.form.operation === 'exchange' || this.form.operation === 'zero') {
        delete form['refund_channel']
      }
      if(this.form.operation === 'zero'){
        delete form['express_num']
      }
      //补发
      if (this.form.operation === 'again') {
        delete form['refund_channel']
        delete form['description']
        delete form['return_address']
      }
      // 钱包退款：用 front_select_unique_key 匹配，取出 wallet_type 和 custom_wallet_id
      if (this.form.refund_channel === 'wallet' && this.form.front_select_unique_key) {
        const selectedWallet = this.walletList.find(item => item.front_select_unique_key === this.form.front_select_unique_key)
        if (selectedWallet) {
          form.custom_wallet_id = selectedWallet.custom_wallet_id
          form.wallet_type = selectedWallet.value
        }
        // 清理前端字段，不提交给接口
        delete form['front_select_unique_key']
      }
      Object.keys(form).map(k => {
        let key = this.getMap(k, false)
        temp[key] = form[k]
      })
      this.changeTableRefresh = Date.now()
      this.$emit('handleConfirm', temp)
    },
    handleDialogClear () {
      this.handleCustom({
        action: "clearChangeList"
      })
      this.$set(this.product, 'num', '')
    },
    //dialog==================
    /**添加换货商品**/
    handleAddChange (product) {
      console.log(product, 'aaas')
      this.handleCustom({
        action: 'getChangeProductInfo',
        data: { product }
      })
    },
    /**已选换货移除**/
    handleTableClick ({ row, value, index, rowIndex }) {
      console.log(row, value, index, rowIndex)
      this.handleCustom({
        action: 'remove',
        data: { rowIndex }
      })
    },
    //查看明细
    lookDetailed(row){
      this.$emit('showDialog',row)
    },

     //table disabled
    handleSelectionRowIsDisabled(item,type){
      if (item.can_use_sale_price===0&&item.can_use_purchase_price===0&&type==='refund_and_good') return false
      return true
    },

    handleTableEdit({header,row,index}){
      console.log(this.form,header,row,index,'aaaaaa')
      console.log(header,'aaaaaa')
      if(header.prop==="refund_purchase_price"&&row.is_calc_refund_sale_price==='Y'){
        if(row.refund_purchase_price*100>this.tableList[index]['can_use_purchase_price']){
          this.$message.error('退款金额不能大于可退金额')
          row.refund_purchase_price = this.tableList[index]['can_use_purchase_price']/100
          row.refund_sale_price = this.tableList[index]['can_use_sale_price']
          this.$set(this.tableList,index,row)
          this.tableRefresh = Date.now()
          return
        }
        if(row['refund_purchase_price']*100!==this.tableList[index]['can_use_purchase_price']){
          row.refund_sale_price = Math.ceil((row.refund_purchase_price*100)*(this.$xdHelper.divisionFloatNumber(row.refund_dist_channel_proportion, 10000)))
          this.$set(this.tableList,index,row)
          this.tableRefresh = Date.now()
        }else{
          row.refund_sale_price = this.tableList[index]['can_use_sale_price']
          this.$set(this.tableList,index,row)
          this.tableRefresh = Date.now()
        }
      }
      if(header.prop==="refund_sale_price"&&row.is_calc_refund_purchase_price==='Y'){
        if(row.refund_sale_price*100>this.tableList[index]['can_use_sale_price']){
          this.$message.error('退款金额不能大于可退金额')
          row.refund_sale_price = this.tableList[index]['can_use_sale_price']/100
          row.refund_purchase_price = this.tableList[index]['can_use_purchase_price']
          this.$set(this.tableList,index,row)
          this.tableRefresh = Date.now()
          return
        }
        if(row['refund_sale_price']*100!==this.tableList[index]['can_use_sale_price']){
          row.refund_purchase_price = Math.ceil((row.refund_sale_price*100)*(this.$xdHelper.divisionFloatNumber(row.refund_dist_channel_proportion, 10000)))
          console.log((row.refund_sale_price*100)*(this.$xdHelper.divisionFloatNumber(row.refund_dist_channel_proportion, 10000)),'aaaaaac')
          this.$set(this.tableList,index,row)
          this.tableRefresh = Date.now()
        }else{
          row.refund_purchase_price = this.tableList[index]['can_use_purchase_price']
          this.$set(this.tableList,index,row)
        }
      }
      if(this.form.selectTableList&&this.form.selectTableList.length){
        let getIndex
        if(row.sku_id){
          getIndex = this.form.selectTableList.findIndex(item=>{
            return item.product_id===row.product_id&&item.sku_id===row.sku_id
          })
        }else{
           getIndex = this.form.selectTableList.findIndex(item=>{
            return item.product_id===row.product_id
          })
        }
        console.log(getIndex,'gggg')
        this.$set(this.form.selectTableList,getIndex,row)
        console.log(this.form.selectTableList,getIndex,row,'rrrrrr')
      }
    },

    // 处理退款金额编辑保存
    handleRefundSalePriceSave(row, cb, status) {
      let index = this.tableList.findIndex(item => item.product_id === row.product_id && item.sku_id === row.sku_id)
      if (index === -1) {
        index = this.tableList.findIndex(item => item.product_id === row.product_id)
      }

      // 验证退款金额是否超过可退金额，超过则恢复默认值
      if (row.refund_sale_price * 100 > this.tableList[index]['can_use_sale_price']) {
        this.$message.error('退款金额不能大于可退金额')
        // 更新 tableList
        this.$set(this.tableList, index, row)
        this.tableRefresh = Date.now()
        // 返回 false 让组件恢复为旧值
        cb && cb(false)
        return
      }

      // 同步到 selectTableList
      if (this.form.selectTableList && this.form.selectTableList.length) {
        let getIndex
        if (row.sku_id) {
          getIndex = this.form.selectTableList.findIndex(item => {
            return item.product_id === row.product_id && item.sku_id === row.sku_id
          })
        } else {
          getIndex = this.form.selectTableList.findIndex(item => {
            return item.product_id === row.product_id
          })
        }
        this.$set(this.form.selectTableList, getIndex, row)
      }

      // 同步 tableList
      this.$set(this.tableList, index, row)
      this.tableRefresh = Date.now()
      cb && cb(status)

      // 如果供货商退款金额不可编辑，自动计算供货商退款金额
      if (row.is_edit_refund_purchase_price !== 'Y') {
        this.handleAutoCalcRefundPurchasePrice(row)
      }
    },

    // 处理供应商退款金额编辑保存
    handleRefundPurchasePriceSave(row, cb, status) {
      let index = this.tableList.findIndex(item => item.product_id === row.product_id && item.sku_id === row.sku_id)
      if (index === -1) {
        index = this.tableList.findIndex(item => item.product_id === row.product_id)
      }

      // 验证退款金额是否超过可退金额，超过则恢复默认值
      if (row.refund_purchase_price * 100 > this.tableList[index]['can_use_purchase_price']) {
        this.$message.error('退款金额不能大于可退金额')
        // 更新 tableList
        this.$set(this.tableList, index, row)
        this.tableRefresh = Date.now()
        // 返回 false 让组件恢复为旧值
        cb && cb(false)
        return
      }

      // 同步到 selectTableList
      if (this.form.selectTableList && this.form.selectTableList.length) {
        let getIndex
        if (row.sku_id) {
          getIndex = this.form.selectTableList.findIndex(item => {
            return item.product_id === row.product_id && item.sku_id === row.sku_id
          })
        } else {
          getIndex = this.form.selectTableList.findIndex(item => {
            return item.product_id === row.product_id
          })
        }
        this.$set(this.form.selectTableList, getIndex, row)
      }

      // 同步 tableList
      this.$set(this.tableList, index, row)
      this.tableRefresh = Date.now()
      cb && cb(status)

      // 如果用户退款金额不可编辑，自动计算用户退款金额
      if (row.is_edit_refund_sale_price !== 'Y') {
        this.handleAutoCalcRefundSalePrice(row)
      }
    },

    // 自动计算用户退款金额（根据供货商退款金额计算）
    // 公式：本次用户退款金额 = 本次供货商退款金额 / (refund_dist_channel_proportion / 10000)
    handleAutoCalcRefundSalePrice(row) {
      let index = this.tableList.findIndex(item => item.product_id === row.product_id && item.sku_id === row.sku_id)
      if (index === -1) {
        index = this.tableList.findIndex(item => item.product_id === row.product_id)
      }

      // 获取备份数据
      let backupData = {
        refund_sale_price: row._backup_refund_sale_price,
        refund_purchase_price: row._backup_refund_purchase_price
      }

      // 如果当前输入的供货商退款金额等于备份值，直接使用备份的用户退款金额
      if (backupData && row.refund_purchase_price == backupData.refund_purchase_price) {
        row.refund_sale_price = backupData.refund_sale_price
        this.$set(this.tableList, index, row)
        this.tableRefresh = Date.now()

        if (this.form.selectTableList && this.form.selectTableList.length) {
          let getIndex = this.form.selectTableList.findIndex(item => {
            return item.product_id === row.product_id && item.sku_id === row.sku_id
          })
          if (getIndex === -1 && row.sku_id) {
            getIndex = this.form.selectTableList.findIndex(item => item.product_id === row.product_id)
          }
          if (getIndex !== -1) {
            this.$set(this.form.selectTableList, getIndex, row)
          }
        }

        this.$message.success('已使用备份值')
        return
      }

      let proportion = row.refund_dist_channel_proportion || 0
      if (proportion <= 0) {
        this.$message.error('退款比例为0，无法计算')
        return
      }

      // 计算：本次用户退款金额 = 本次供货商退款金额 / (refund_dist_channel_proportion / 10000)
      // 如果只有供货商退款金额可编辑（type:'price'列为分），结果需*100转为分
      // 如果两个都能编辑（都是输入框），不需要*100
      let refundSalePrice = row.refund_purchase_price / (this.$xdHelper.divisionFloatNumber(proportion, 10000))
      if (row.is_edit_refund_sale_price === 'N') {
        refundSalePrice = refundSalePrice * 100
      }

      // 保留两位小数
      refundSalePrice = Number(refundSalePrice.toFixed(2))

      // 更新值
      row.refund_sale_price = refundSalePrice
      this.$set(this.tableList, index, row)
      this.tableRefresh = Date.now()

      // 同步到 selectTableList
      if (this.form.selectTableList && this.form.selectTableList.length) {
        let getIndex
        if (row.sku_id) {
          getIndex = this.form.selectTableList.findIndex(item => {
            return item.product_id === row.product_id && item.sku_id === row.sku_id
          })
        } else {
          getIndex = this.form.selectTableList.findIndex(item => {
            return item.product_id === row.product_id
          })
        }
        this.$set(this.form.selectTableList, getIndex, row)
      }

      this.$message.success('已自动计算用户退款金额')
    },

    // 自动计算供货商退款金额（根据用户退款金额计算）
    // 公式：本次供货商退款金额 = 本次用户退款金额 * (refund_dist_channel_proportion / 10000)
    handleAutoCalcRefundPurchasePrice(row) {
      let index = this.tableList.findIndex(item => item.product_id === row.product_id && item.sku_id === row.sku_id)
      if (index === -1) {
        index = this.tableList.findIndex(item => item.product_id === row.product_id)
      }

      // 获取备份数据
      let backupData = {
        refund_sale_price: row._backup_refund_sale_price,
        refund_purchase_price: row._backup_refund_purchase_price
      }

      // 如果当前输入的用户退款金额等于备份值，直接使用备份的供货商退款金额
      if (backupData && row.refund_sale_price == backupData.refund_sale_price) {
        row.refund_purchase_price = backupData.refund_purchase_price
        this.$set(this.tableList, index, row)
        this.tableRefresh = Date.now()

        if (this.form.selectTableList && this.form.selectTableList.length) {
          let getIndex = this.form.selectTableList.findIndex(item => {
            return item.product_id === row.product_id && item.sku_id === row.sku_id
          })
          if (getIndex === -1 && row.sku_id) {
            getIndex = this.form.selectTableList.findIndex(item => item.product_id === row.product_id)
          }
          if (getIndex !== -1) {
            this.$set(this.form.selectTableList, getIndex, row)
          }
        }

        this.$message.success('已使用备份值')
        return
      }

      let proportion = row.refund_dist_channel_proportion || 0
      if (proportion <= 0) {
        this.$message.error('退款比例为0，无法计算')
        return
      }

      // 计算：本次供货商退款金额 = 本次用户退款金额 * (refund_dist_channel_proportion / 10000)
      // 如果只有用户退款金额可编辑（输入框为元），结果需*100转为分存入price列
      // 如果两个都能编辑（都是输入框），不需要*100
      let refundPurchasePrice = row.refund_sale_price * (this.$xdHelper.divisionFloatNumber(proportion, 10000))
      if (row.is_edit_refund_purchase_price === 'N') {
        refundPurchasePrice = refundPurchasePrice * 100
      }

      // 保留两位小数
      refundPurchasePrice = Number(refundPurchasePrice.toFixed(2))

      // 更新值
      row.refund_purchase_price = refundPurchasePrice
      this.$set(this.tableList, index, row)
      this.tableRefresh = Date.now()

      // 同步到 selectTableList
      if (this.form.selectTableList && this.form.selectTableList.length) {
        let getIndex
        if (row.sku_id) {
          getIndex = this.form.selectTableList.findIndex(item => {
            return item.product_id === row.product_id && item.sku_id === row.sku_id
          })
        } else {
          getIndex = this.form.selectTableList.findIndex(item => {
            return item.product_id === row.product_id
          })
        }
        this.$set(this.form.selectTableList, getIndex, row)
      }

      this.$message.success('已自动计算供货商退款金额')
    },

    add(item) {
      if(!item['supplier_id']||(!item['score']&&item['score']!==0)){
        this.$message.error('请完善信息')
        return
      }
      this.setting.scoringData.push({supplier_id:'',score:''});
    },
    remove(index) {
      this.setting.scoringData.splice(index, 1);
    },
  }
}
</script>

<style scoped lang="scss">
::v-deep .xd-store-product {
  & > div {
    padding: 0;
  }
}

.xd-customer-operation {
  &__dialog {
    &-operation {
      &-item {
        ::v-deep .el-input__icon.el-input__validateIcon {
          display: none !important;
        }

        display: flex;
        justify-content: flex-start;
        align-items: center;
        margin-bottom: 15px;

        &:last-child {
          margin-bottom: 0;
        }

        & > div:first-child {
          width: 86px;
          flex-shrink: 0;
          text-align: left;
        }
      }
    }

    &-title {
      border-top: 1px solid #f8f8f8;
      margin-top: 10px;
      height: 50px;
      display: flex;
      justify-content: flex-start;
      align-items: center;

      & > div:nth-child(1) {
        text-align: left;
        font-weight: bold;
        color: #111;
        margin-right: 10px;
        flex-shrink: 0;
      }

      & > div:nth-child(2) {
        display: flex;
        justify-content: flex-start;
        align-items: flex-end;
        font-size: 12px;
      }
    }

    &-options {
      padding: 10px 0 0;

      ::v-deep .el-input__icon.el-input__validateIcon {
        display: none !important;
      }

      & > div {
        display: flex;
        justify-content: flex-start;
        align-items: flex-start;
        line-height: 36px;

        & > div:nth-child(1) {
          width: 86px;
          flex-shrink: 0;
          text-align: left;
          font-size: 13px;
        }

        & > div:nth-child(2) {
          flex: 1;
        }
      }

      .express {
        display: flex;
        justify-content: flex-start;
        align-items: center;

        & > *:nth-child(1) {
          margin-right: 10px;
        }
      }
    }
  }
}

@media screen and (max-width: 768px) {
  .xd-customer-operation {
  }
}

.xd-customer-operation__dialog-change-search {
  &-title {
    height: 50px;
    margin: 10px 0;
    font-weight: bold;
    color: #111;
  }

  &-select {
    display: flex;

    & > div:first-child {
      min-width: 100px;
    }

    &-chose {
      display: flex;
      flex-wrap: wrap;
    }
  }
}

.xd-customer-operation__dialog-change-title {
  height: 50px;
  margin: 10px 0;
  font-weight: bold;
  color: #111;
}
.product_base{
    display:flex;
    flex-wrap: wrap;
    &_item{
      display:flex;
      flex-wrap: wrap;
      margin: 10px 40px 10px 0;
      font-size: 14px;
      position: relative;
      &>span:first-child{
        color: #606266;
      }
      &>span:nth-child(2){
        color: #333;
        padding-left: 10px;
      }
      &>i{
        position: absolute;
        right: -15px;
        top:-10px;
      }
    }
  }
  .red{
    color: red;
  }
</style>
