<!--日志列表-->
<template>
  <el-main class="bg_white wrap_box lcpg">
    <!-- 搜索栏-->
    <el-form :model="searchdata" ref="searchform">
      <el-row>
        <el-col :span="4"><el-form-item label="类型" prop="type">
            <el-select v-model="searchdata.type" clearable>
              <el-option v-for="it in data.typelist" :value="it.value" :label="it.label" :key="it.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="3" ><el-form-item label="规格型号(SKU)" prop="sku" >
            <el-input v-model="searchdata.sku" />
          </el-form-item>
        </el-col>
        <el-col :span="3" style="margin-left: 5%;"><el-form-item label="产品名称" prop="name">
            <el-input v-model="searchdata.name" />
          </el-form-item>
        </el-col>
        <el-col :span="4" style="margin-left: 3%;"><el-form-item label="产品分类" prop="cate_id">
            <el-cascader :disabled="data.isDisabled" v-model="searchdata.cate_id" :show-all-levels="false" clearable
              :options="data.catelist" :props="data.cateprops" />
          </el-form-item>
        </el-col>
        <el-col :span="4"><el-form-item label="特价状态" prop="status">
            <el-select v-model="searchdata.status" placeholder="请选择">
              <el-option v-for="it in data.statelist" :value="it.value" :label="it.label" :key="it.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="4"> <el-form-item label="库存变现状态" prop="stock_status">
            <el-select v-model="searchdata.stock_status" placeholder="请选择">
              <el-option v-for="it in data.inventorystatuslist" :value="it.value" :label="it.label"
                :key="it.value"></el-option>
            </el-select>
          </el-form-item>
        </el-col>
        
      </el-row>
      <el-row>
         <el-col :span="4" ><el-form-item label="编号" prop="promotion_sn">
            <el-input v-model="searchdata.promotion_sn" />
          </el-form-item>
        </el-col>
         <el-col :span="4" ><el-form-item label="部门" prop="depart">
            <el-input v-model="searchdata.depart" />
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <el-form-item>
            <div class="s-bts">
              <div class="l-button" @click="searchhandle">搜索</div>
              <div class="l-button" @click="resetSearch">重置</div>
            </div>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <div class="s-bts tjbj" style="justify-content: flex-start;">
      <div class="l-button" style="margin-right: 10px;" @click="jumpPage('add')" v-if="data.auth_write == 1">新增</div>
      <el-dropdown :hide-on-click="false">
        <div class="l-button btcz">操作<el-icon class="el-icon--right"><arrow-down /></el-icon></div>
        <template #dropdown>
          <el-dropdown-menu>
            <el-dropdown-item @click="xzmb" v-if="data.auth_write == 1">下载模板</el-dropdown-item>
            <el-dropdown-item @click="exportIn" v-if="data.auth_write == 1">
              <el-upload :action="data.upLoadUrl" :with-credentials="true" :on-success="handleSuccess"
                :show-file-list="false" name="file" :limit="1" accept=".xls,.xlsx" :before-upload="beforeAvatarUpload"
                ref="uploadwlbj">
                <div>导入</div>
              </el-upload>
            </el-dropdown-item>
            <el-dropdown-item @click="exportOut">导出</el-dropdown-item>
            <el-dropdown-item @click="isiteffective('loseefficacy')" v-if="data.auth_write == 1">强制失效</el-dropdown-item>
            <el-dropdown-item @click="isiteffective('takeeffect')" v-if="data.auth_write == 1">强制生效</el-dropdown-item>
            <el-dropdown-item @click="syncInventoryData" v-if="data.auth_write == 1">库存数据刷新</el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <!-- 表格-->
    <div>
      <vxe-table @checkbox-change="selectionChange" @checkbox-all="selectionallChange" max-height="620" border
        show-overflow :data="data.prlistTtable" class="ggdycss">
        <vxe-column type="checkbox" width="40" fixed="left"></vxe-column>
        <vxe-column field="promotion_sn" title="编号" width="150" align="center"></vxe-column>
        <vxe-column field="depart" title="部门" width="180" align="left"></vxe-column>
        <vxe-column field="type" title="类型" width="110" align="center"></vxe-column>
        <vxe-column field="sku" title="规格型号(SKU)" width="225" align="left" fixed="left">
          <template #default="{ row }">
            <span @click="jumpPage('edit', row.id)" style="color: #409eff;cursor: pointer;">{{ row.sku }}</span>
          </template>
        </vxe-column>
        <vxe-column field="name" title="名称" width="200" align="left" fixed="left"></vxe-column>
        <vxe-column field="cate_name" title="产品分类" width="250" align="left"></vxe-column>
        <vxe-column field="stock_status" title="库存变现状态" width="95" align="center">
        </vxe-column>
        <vxe-column field="stock_start_time" title="库存变现生效日期" width="95" align="center">
        </vxe-column>
        <vxe-column field="stock_end_time" title="库存变现失效日期" width="95" align="center">
        </vxe-column>
        <vxe-column field="factory_price" title="出厂价" width="90" align="right">
        </vxe-column>
        <vxe-column field="price" title="清库核算价格/清库特价" width="90" align="right">
        </vxe-column>
        <vxe-column field="discount" title="清库折扣力度" width="95" align="right">
        </vxe-column>
        <vxe-column field="domestic_retail_price" title="建议国内零售限价(￥)" width="85" align="right">
        </vxe-column>
        <vxe-column field="overseas_retail_price" title="建议海外零售限价($)" width="85" align="right">
        </vxe-column>
        <vxe-column field="total_stock" title="成品仓库存总量" width="70" align="right">
        </vxe-column>
        <vxe-column field="orico_cd" title="ORICO-CD库存" width="65" align="right">
        </vxe-column>
        <vxe-column field="orico_od" title="ORICO-OD库存" width="65" align="right">
        </vxe-column>
        <vxe-column field="orico_ad" title="ORICO-AD库存" width="65" align="right">
        </vxe-column>
        <vxe-column field="orico_bd" title="ORICO-BD库存" width="65" align="right">
        </vxe-column>
        <vxe-column field="orico_fd" title="ORICO-FD库存" width="65" align="right">
        </vxe-column>
        <vxe-column field="orico_gd" title="ORICO-GD库存" width="65" align="right">
        </vxe-column>
        <vxe-column field="orico_hd" title="ORICO-HD库存" width="65" align="right">
        </vxe-column>
        <vxe-column field="orico_jd" title="ORICO-JD库存" width="65" align="right">
        </vxe-column>
        <vxe-column field="status" title="特价状态" width="80" align="center">
        </vxe-column>
        <vxe-column field="start_time" title="特价生效日期" width="95" align="center">
        </vxe-column>
        <vxe-column field="end_time" title="特价失效日期" width="95" align="center">
        </vxe-column>
        <vxe-column field="create_time" title="创建日期" width="140" align="center">
        </vxe-column>
        <vxe-column field="update_time" title="最后更新日期" width="140" align="center">
        </vxe-column>
      </vxe-table>
      <!-- 分页-->
      <div class="block">
        <el-pagination background @size-change="handleSizeChange" @current-change="handleCurrentChange"
          :current-page="searchdata.page" :page-sizes="[50, 100, 150]" :page-size="searchdata.size"
          layout="total, sizes, prev, pager, next, jumper" :total="data.total">
        </el-pagination>
      </div>
    </div>
  </el-main>
</template>
<script setup name="specialPromotion">
import { reactive, ref, getCurrentInstance, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router';
import { useStore } from 'vuex'
import { ElMessage } from 'element-plus'
import { exportlist } from '../../utils/lc'
import { ElLoading } from 'element-plus'
// 基本信息组件值
const { proxy } = getCurrentInstance()
//搜索
let searchdata = reactive({
  type: '',//类型 1=停产促销,2=仅第三方仓促销,3=不停产促销,4=战略产品特价
  sku: '',//sku
  name: '',//名称
  cate_id: '',//产品分类
  status: -1,//状态 0=未生效,1=生效中,2=强制生效,3=已失效
  stock_status: -1,// 库存变现状态
  promotion_sn: '',// 编号
  depart:'',// 部门
  page: 1,
  size: 50
})
const apiVersion = process.env.VUE_APP_API_VERSION.replace(/\./g, '_')
const baseUrl = process.env.VUE_APP_API_BASEURL + apiVersion + '/'
const data = reactive({
  auth_write: 0,// 新增编辑权限1是显示
  mbfile: '',
  upLoadUrl: baseUrl + 'promotion/import',
  prlistTtable: [],
  total: 0,
  catelist: [],//产品分类
  typelist: [
    {
      label: '停产促销',
      value: 1,
    }, {
      label: '仅第三方仓促销',
      value: 2
    }, {
      label: '不停产促销',
      value: 3
    }
  ],//分类下拉
  statelist: [
    {
      label: '全部',
      value: -1
    }, {
      label: '生效中',
      value: 1
    }, {
      label: '未生效',
      value: 0
    }, {
      label: '已失效',
      value: 4
    }, {
      label: '强制生效',
      value: 2
    }, {
      label: '强制失效',
      value: 3
    }
  ],//库存状态下拉
  inventorystatuslist: [
    {
      label: '全部',
      value: -1
    }, {
      label: '未生效',
      value: 0
    }, {
      label: '生效中',
      value: 1
    }, {
      label: '已失效',
      value: 2
    }
  ],
  cateprops: {
    expandTrigger: 'hover',
    value: 'id',
    label: 'name',
    children: 'children',
    emitPath: false,
  },
})
/* 初始化 */
const keyDown = (e) => {
  if (e.keyCode == 13 || e.keyCode == 100) {
    searchhandle()
  }
}
onMounted(() => {
  getcatelist()
  // 获取列表数据
  getlist()
  //绑定监听事件
  window.addEventListener('keydown', keyDown)
})
onUnmounted(() => {
  //销毁事件
  window.removeEventListener('keydown', keyDown, false)
})
/* 方法层 */
let router = useRouter()
//获取列表数据
function getcatelist () {
  // 产品分类 - 集合
  proxy.$http.showLoading(true).get('v1/category', { language_id: 1 }).then(res => {
    if (res.status == 200) {
      data.catelist = res.data
    }
  })
}
function getlist () {
  let sudata = JSON.parse(JSON.stringify(searchdata))
  sudata.type = sudata.type ? sudata.type : -1
  proxy.$http.showLoading(true).get('promotion/list', sudata).then((res) => {
    if (res.errno == 200) {
      data.mbfile = res.data.import_file_url
      data.prlistTtable = res.data.list.data
      data.total = res.data.list.total
      data.auth_write = res.data.auth_write
    }
  })
}

const store = useStore()
//下载模板
function xzmb () {
  // 假设这是你要下载的文件的URL  
  const fileUrl = data.mbfile

  // 创建一个a标签  
  const link = document.createElement('a');
  link.href = fileUrl;
  // 设置下载后的文件名（可选，如果服务器响应中包含了正确的Content-Disposition头，则可能不需要）  
  link.setAttribute('download', 'desiredFileName.pdf');

  // 兼容性处理：模拟点击需要添加到document中  
  document.body.appendChild(link);
  link.click();

  // 清理：移除a标签（可选，但推荐）  
  document.body.removeChild(link);
}
// 跳转新增编辑
function jumpPage (type, id) {
  if (type == 'add') {
    router.push({ path: '/index/addspeciapr' })
  }
  if (type == 'edit') {
    // 关闭页签 如果存在 editSpu 先关闭
    let index = null
    store.state.topNavTag.tags.forEach((el, inde) => {
      el.fullPath.indexOf('editspeciapr') != -1 ? index = inde : false
    });
    if (index) {
      store.dispatch('topNavTag/removeNavTag', index)
    }
    router.push({
      path: '/index/editspeciapr', query: {
        id: id
      }
    })
  }
}
//重置
function resetSearch () {
  getcatelist()
  proxy.$refs.searchform.resetFields()
  getlist()
}
// 搜索
function searchhandle () {
  getlist()
}

//分页条数
function handleSizeChange (val) {
  searchdata.size = val
  searchdata.page = 1
  getlist()
}

//分页数
function handleCurrentChange (val) {
  searchdata.page = val
  getlist()
}
const checklist = ref([])

// 导出
function exportOut () {
  let query = {
    page: searchdata.page,
    type: searchdata.type ? searchdata.type : -1,
    sku: searchdata.sku,
    name: searchdata.name,
    cate_id: searchdata.cate_id || '',
    status: searchdata.status ? searchdata.status : -1,
    path: '/promotion/export',
    ids: checklist.value.length == 0 ? '' : checklist.value.join()
  }
  exportlist(null, null, null, null, '导出', query)
}
// 强制失效 强制生效
function isiteffective (type) {
  if (checklist.value.length == 0) {
    ElMessage({
      type: 'error',
      message: type == 'loseefficacy' ? '请先勾选在操作强制失效!' : '请先勾选在操作强制生效!'
    })
    return
  }
  proxy.$http.showLoading(true).post('promotion/editBatch', { ids: checklist.value.join(), status: type == 'loseefficacy' ? 3 : 2 }).then((res) => {
    if (res.errno == 200) {
      ElMessage.success(`${type == 'loseefficacy' ? '强制失效' : '强制生效'}操作成功!`)
      resetSearch()
    } else {
      ElMessage.error(res.errmsg)
    }
  })
}
//导入
let loadingInstance = ref()
function handleSuccess (res) {
  if (res.errno == 200) {
    resetSearch()
    ElMessage.success(res.errmsg)
  } else {
    ElMessage.error(res.errmsg)
  }
  proxy.$refs.uploadwlbj.clearFiles()

  loadingInstance.value.close()

}
//文件校验方法
function beforeAvatarUpload (file) {
  loadingInstance.value = ElLoading.service({
    lock: true,
    text: '此操作需要一段时间请耐心等待！',
    background: 'rgba(0, 0, 0, 0.7)',
  })
  //不能导入大小超过20Mb的文件
  if (file.size > 20 * 1024 * 1024) {
    ElMessage({ type: 'error', message: '文件过大，请上传小于20MB的文件!' })

    loadingInstance.value.close()

    return false
  }
  return true
}
// 列表单选
function selectionChange (val) {
  checklist.value = val.records.map(it => { return it.id })
}
// 列表全选
function selectionallChange (val) {
  checklist.value = val.records.map(it => { return it.id })
}
// 库存数据刷新
function syncInventoryData () {
  proxy.$http.showLoading(true).post('promotion/syncStock').then((res) => {
    if (res.errno == 200) {
      ElMessage.success(res.errmsg)
      resetSearch()
    } else {
      ElMessage.error(res.errmsg)
    }
  })
}
</script>
<style scoped lang="scss">
@import "../../assets/style/lc.scss";

.tjbj {
  margin-bottom: 20px;
}

.btcz {
  display: flex;
  flex-direction: row;
  align-items: center;
  padding: 7px 16px;
}

::v-deep(.el-input) {
  width: 185px !important;
}

::v-deep(.el-cascader .el-input) {
  width: 200px !important;
}
::v-deep(.el-form-item){
  margin-bottom: 15px !important;
}
.bjbt {
  border: 1px solid #409eff;
  font-size: 12px;
  color: #409eff;
  height: 30px;
}

</style>
