<!--
 * @Description : 产品目录清单 - 新增sku - 拖拽弹窗
 * @Author      : jinxin
 * @Date        : 2022-10-20 09:32:47
-->

<template>
  <div>
    <vxe-modal :model-value="isShow" id="myModal6" width="340" @close="clickCloseMe" height="90" min-width="260"
      min-height="300" :show-close="data.isClose" :lockView="false" :mask="false" remember storage>
      <template #title>
        <span style="color: red;">SPU|SKU|暂存|保存 - 任务管理</span>
      </template>
      <template #default>
        <el-progress :percentage="data.progress" :status="data.isStatus" :indeterminate="false" />
      </template>
    </vxe-modal>
  </div>
</template>
<script>
import { defineComponent, onMounted, reactive, inject, getCurrentInstance } from 'vue'
import { useStore } from 'vuex'

export default defineComponent({
  name: 'EditSpuSkuDiaLog',
  props: {
    isShow: {
      type: Boolean,
      default: false
    }
  },
  emits: ['update:isShow', 'getIfClose', 'isSureClosePage'],

  setup (props, context) {
    // 生命周期
    onMounted(() => {
      // 新增进入
      if (requestData) {
        // console.log('requestData',requestData)
        createSpuData()
      }
      if (requestDataEdit) {
        // console.log('requestDataEdit',requestDataEdit)
        editSkuData()
      }
      // 编辑进入
    })
    // 实例
    const { proxy } = getCurrentInstance()
    let store = useStore()
    // 父子
    const requestData = inject('requestData')
    const requestDataEdit = inject('requestDataEdit')
    // 定义变量
    let data = reactive({
      requestData: [],
      progress: 0,
      count: 0,
      isStatus: '',
      clickClose: false,
      num: 1,
    })
    // 提交新增数据
    const createSpuData = async () => {
      console.log('requestData', requestData)
      data.count = 0
      data.num = 1
      let errorNUm = 0
      let spuUrlstaging = requestData.type == 'staging' ? 'v1/product/temp_save' : 'v1/product'
      let skuUrlstaging = requestData.type == 'staging' ? 'v1/product/sku_loop_temp_add' : 'v1/product/sku_loop_add'
      let errorList = []
      // 首次请求数据
      requestData.transmitRquest.sku = requestData.transmitRquest.sku.filter(it => it.sku != '')
      // console.log('frist request data',requestData.transmitRquest)
      let firstQueryData = JSON.parse(JSON.stringify(requestData.transmitRquest))
      firstQueryData.sku = [JSON.parse(JSON.stringify(requestData.transmitRquest.sku[0]))]
      firstQueryData.sku_params = [JSON.parse(JSON.stringify(requestData.transmitRquest.sku_params[0]))]

      requestData.type == 'staging' ? firstQueryData.sku[0].is_temp = 1 : firstQueryData.sku[0].is_temp = 0
      data.count = requestData.transmitRquest.sku.length
      await proxy.$http.post(spuUrlstaging, firstQueryData).then(res => {
        if (res.status == 200) {
          // console.log('res 200',res.data)
          data.progress = Math.floor(data.num / data.count * 100)
          // 是否存在多个sku
          if (requestData.transmitRquest.sku.length > 1) {
            requestData.transmitRquest.sku.forEach((el, ind) => {
              // 排除第一条数据 有数据存在 next
              if (ind && ind <= requestData.transmitRquest.sku.length - 1) {
                let nextQueryData = JSON.parse(JSON.stringify(requestData.transmitRquest))
                nextQueryData.sku = [JSON.parse(JSON.stringify(requestData.transmitRquest.sku[ind]))]
                nextQueryData.sku_params = [JSON.parse(JSON.stringify(requestData.transmitRquest.sku_params[ind]))]
                requestData.type == 'staging' ? nextQueryData.sku[0].is_temp = 1 : nextQueryData.sku[0].is_temp = 0
                let queryPara = {
                  language_id: nextQueryData.language_id,
                  product_id: res.data.product_id,
                  sku: nextQueryData.sku,
                  sku_params: nextQueryData.sku_params
                }
                console.log('queryPara', queryPara)
                proxy.$http.post(skuUrlstaging, queryPara).then(r => {
                  if (r.status == 200) {
                    data.num = data.num + 1
                    data.progress = Math.floor(((data.num) / data.count) * 100)
                  } else {
                    errorNUm = errorNUm + 1
                    errorList.push(queryPara)
                  }
                  if ((data.num + errorNUm) == data.count) {
                    // console.log('errorList ---> ',errorList)
                    let titleStr = ''
                    let indexList = []
                    if (errorList.length > 0) {
                      errorList.forEach(el => {
                        indexList.push(requestData.skuTableInfo.originData.filter(it => it.sku == el.sku[0].sku)[0])
                      });
                      indexList.sort(compare("index"))
                      indexList.forEach(el => {
                        titleStr = titleStr + el.index + ','
                      });
                      if (titleStr.charAt(titleStr.length - 1) == ',') {
                        titleStr = titleStr.slice(0, titleStr.length - 1)
                      }
                      proxy.$message.error('第' + titleStr + '行,数据添加失败!')

                      setTimeout(() => {
                        context.emit('getIfClose')
                      }, 2000)

                    } else {
                      data.progress = 100
                      data.isClose = true
                      // requestData.type == 'save' 给出提示
                      setTimeout(() => {
                        data.isStatus = "success"
                        context.emit('isSureClosePage', true)
                      }, 2000)
                    }
                  }
                })
              }
            })
          } else {
            setTimeout(() => {
              data.isStatus = "success"
              context.emit('isSureClosePage', true)
            }, 2000)
          }
        } else {
          setTimeout(() => {
            data.isClose = true
            data.isStatus = "exception"
            context.emit('getIfClose')
          }, 2000)
        }
      })
    }
    // 编辑数据
    const editSkuData = async () => {
      // console.log('edit save')
      data.count = 0
      data.num = 1
      // console.log('state edit data')
      // console.log('requestDataEdit',requestDataEdit)
      let errorList = []
      let errorNUm = 0
      // 请求方式 put post 请求地址 编辑、新增
      let requestType = ''
      let requestUrl = ''
      requestDataEdit.transmitRquest.sku = requestDataEdit.transmitRquest.sku.filter(it => it.sku != '')
      let firstQueryData = {}
      firstQueryData.language_id = store.state.user.language.id || 1
      firstQueryData.sku = [requestDataEdit.getReqData.outData[0].sku[0]]
      firstQueryData.sku_params = [requestDataEdit.getReqData.outData[0].sku_params[0]]
      firstQueryData.sku_params[0].product_sku_params_id = requestDataEdit.getReqData.originData[0].product_sku_params_id
      firstQueryData.sku_del = requestDataEdit.getReqData.delList
      // 判断 新增、编辑数据
      if (requestDataEdit.getReqData.originData[0].product_sku_id != undefined) {
        firstQueryData.sku[0].product_sku_id = requestDataEdit.getReqData.originData[0].product_sku_id
        requestType = 'put'
        requestUrl = requestDataEdit.getReqData.reqUrl
        firstQueryData.sku[0].is_temp = 0
      } else {
        firstQueryData.sku[0].product_sku_id = ''
        requestType = 'post'
        requestUrl = 'v1/product/sku_loop_add'
        firstQueryData.product_id = requestDataEdit.getReqData.originData[0].product_id
        firstQueryData.sku[0].is_temp = 0
      }
      data.count = requestDataEdit.transmitRquest.sku.length

      await proxy.$http[requestType](requestUrl, firstQueryData).then(res => {
        if (res.status == 200) {
          data.progress = Math.floor(data.num / data.count * 100)
          if (requestDataEdit.transmitRquest.sku.length > 1) {
            requestDataEdit.transmitRquest.sku.forEach((el, ind) => {
              if (ind && ind <= requestDataEdit.transmitRquest.sku.length - 1) {

                let nextQueryData = {}
                nextQueryData.language_id = store.state.user.language.id || 1
                nextQueryData.sku = [JSON.parse(JSON.stringify(requestDataEdit.getReqData.outData[0].sku[ind]))]
                nextQueryData.sku_params = [JSON.parse(JSON.stringify(requestDataEdit.getReqData.outData[0].sku_params[ind]))]
                nextQueryData.sku_params[0].product_sku_params_id = requestDataEdit.getReqData.originData[ind].product_sku_params_id
                if (requestDataEdit.getReqData.originData[ind].product_sku_id != undefined) {
                  nextQueryData.sku[0].product_sku_id = JSON.parse(JSON.stringify(requestDataEdit.getReqData.originData[ind].product_sku_id))
                  requestType = 'put'
                  requestUrl = requestDataEdit.getReqData.reqUrl
                  nextQueryData.sku[0].is_temp = 0
                } else {
                  nextQueryData.sku[0].product_sku_id = ''
                  requestType = 'post'
                  requestUrl = 'v1/product/sku_loop_add'
                  nextQueryData.product_id = requestDataEdit.getReqData.originData[0].product_id
                  nextQueryData.sku[0].is_temp = 0
                }
                nextQueryData.sku_del = requestDataEdit.getReqData.delList
                console.log('edit sku', nextQueryData)
                proxy.$http[requestType](requestUrl, nextQueryData).then(r => {
                  if (r.status == 200) {
                    data.num = data.num + 1
                    data.progress = Math.floor((data.num / data.count) * 100)
                  } else {
                    errorNUm = errorNUm + 1
                    errorList.push(nextQueryData)
                  }
                  if ((data.num + errorNUm) == data.count) {
                    let titleStr = ''
                    let indexList = []
                    if (errorList.length > 0) {
                      errorList.forEach(el => {
                        indexList.push(requestDataEdit.skuTableInfo.originData.filter(it => it.sku == el.sku[0].sku)[0])
                      });
                      indexList.sort(compare("index"))
                      indexList.forEach(el => {
                        titleStr = titleStr + el.index + ','
                      });
                      if (titleStr.charAt(titleStr.length - 1) == ',') {
                        titleStr = titleStr.slice(0, titleStr.length - 1)
                      }
                      proxy.$message.error('第' + titleStr + '行,数据添加失败!')
                      setTimeout(() => {
                        context.emit('getIfClose')
                      }, 2000)
                    } else {
                      data.progress = 100
                      data.isClose = true
                      // 给出提示
                      proxy.$message.success('金蝶同步请求已提交,具体同步情况通过[同步任务列表]查看')
                      setTimeout(() => {
                        data.isStatus = "success"
                        context.emit('getIfClose')
                        location.reload()
                        // 编辑数据 无需关闭当前页
                        // context.emit('isSureClosePage',true)
                      }, 2000)
                    }
                  }
                })
              }
            })
          } else {
            proxy.$message.success('金蝶同步请求已提交,具体同步情况通过[同步任务列表]查看')
            data.isStatus = "success"
            data.isClose = true
            context.emit('getIfClose')
            location.reload()
          }
        } else {
          data.isClose = true
          data.isStatus = "exception"
          context.emit('getIfClose')
        }
      })
    }
    // 排序
    const compare = (property) => {
      return (a, b) => {
        let valueO = a[property]
        let valueT = b[property]
        return valueO - valueT
      }
    }
    // 手动关闭
    const clickCloseMe = () => {
      data.clickClose = true
      context.emit('getIfClose', data.clickClose)
    }
    return {
      data,
      requestData,
      props,
      createSpuData,
      clickCloseMe,
      editSkuData,
      compare
    }
  }
})
</script>
<style scoped>
::v-deep(.vxe-modal--wrapper) {
  z-index: 100000 !important;
}
</style>