<template>
  <div class="koi-flex">
    <KoiCard>
      <!-- 搜索条件 -->
      <el-form v-show="showSearch" :inline="true">
        <el-form-item label="阶级价格" prop="rank">
          <el-select
            v-model="searchParams.rank"
            clearable
            placeholder="阶级价格"
            @change="getList"
            style="width: 160px"
          >
            <el-option
              v-for="item in casteList"
              :key="item.value"
              :label="item.name"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建时间" prop="createTimes">
          <el-date-picker
            v-model="createTimes"
            :teleported="false"
            end-placeholder="结束日期"
            range-separator="至"
            start-placeholder="开始日期"
            style="width: 240px"
            type="daterange"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>

        <el-form-item>
<!--          <PopoverWrapper width="450px">-->
<!--            <el-form :inline="true" label-width="100px">-->
<!--              <el-form-item label="品牌" prop="brand">-->
<!--                <el-select-->
<!--                  v-model="searchParams.brand"-->
<!--                  :teleported="false"-->
<!--                  clearable-->
<!--                  filterable-->
<!--                  placeholder="品牌"-->
<!--                  style="width: 260px"-->
<!--                >-->
<!--                  <el-option-->
<!--                    v-for="item in brandList"-->
<!--                    :key="item.recordId"-->
<!--                    :label="item.brand"-->
<!--                    :value="item.brand"-->
<!--                  />-->
<!--                </el-select>-->
<!--              </el-form-item>-->
<!--              <el-form-item label="型号" prop="modelNum">-->
<!--                <el-input-->
<!--                  v-model="searchParams.modelNum"-->
<!--                  clearable-->
<!--                  placeholder="请输入型号"-->
<!--                  style="width: 260px"-->
<!--                  @keyup.enter.native="getList"-->
<!--                ></el-input>-->
<!--              </el-form-item>-->
<!--              <el-form-item label="参数" prop="argument">-->
<!--                <el-input-->
<!--                  v-model="searchParams.argument"-->
<!--                  clearable-->
<!--                  placeholder="请输入参数"-->
<!--                  style="width: 260px"-->
<!--                  @keyup.enter.native="getList"-->
<!--                ></el-input>-->
<!--              </el-form-item>-->
<!--            </el-form>-->
<!--          </PopoverWrapper>-->
          <el-button v-throttle="getList" icon="search" plain type="primary">搜索</el-button>
          <el-button v-throttle="resetSearch" icon="refresh" plain type="danger">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 表格头部按钮 -->
      <el-row :gutter="10">
        <el-col :span="1.5">
          <el-button v-authth="['item:product:import']" icon="Upload" plain type="success" @click="uploadFile">上传</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button v-authth="['item:product:import']" icon="Upload" plain type="success">导入单价</el-button>
        </el-col>
        <el-col :span="1.5">
          <el-button icon="Download" plain type="primary" @click="handleExport">导出</el-button>
        </el-col>
        <el-col v-auth="['item:product:del']" :span="1.5">
          <el-button :disabled="multiple" icon="delete" plain type="danger" @click="handleBatchDelete()">批量删除</el-button>
        </el-col>
        <KoiToolbar v-model:showSearch="showSearch" @refreshTable="getList"></KoiToolbar>
      </el-row>

      <div class="h-20px"></div>
      <el-table
        v-loading="loading"
        :data="tableList"
        :header-cell-style="{ background: '#f1f1f1', color: '#000000' }"
        border
        empty-text="暂时没有数据哟"
        default-expand-all
        :row-style="{ background: '#f9f9f9' }"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="expand">
          <template #default="{ row }">
            <el-row align="middle" justify="start" :gutter="2">
              <el-col :span="3" :offset="1">
                第1阶数量：
                <el-tag v-show="row.rankNumOne" type="primary" style="width: 70px">{{ row.rankNumOne }}</el-tag>
              </el-col>
              <el-col :span="3">
                第2阶数量：
                <el-tag v-show="row.rankNumTwo" type="primary" style="width: 70px">{{ row.rankNumTwo }}</el-tag>
              </el-col>
              <el-col :span="3">
                第3阶数量：
                <el-tag v-show="row.rankNumThree" type="primary" style="width: 70px">{{ row.rankNumThree }}</el-tag>
              </el-col>
              <el-col :span="3">
                第4阶数量：
                <el-tag v-show="row.rankNumFour" type="primary" style="width: 70px">{{ row.rankNumFour }}</el-tag>
              </el-col>
              <el-col :span="3">
                第5阶数量：
                <el-tag v-show="row.rankNumFive" type="primary" style="width: 70px">{{ row.rankNumFive }}</el-tag>
              </el-col>
              <el-col :span="3">
                第6阶数量：
                <el-tag v-show="row.rankNumSix" type="primary" style="width: 70px">{{ row.rankNumSix }}</el-tag>
              </el-col>
            </el-row>

            <el-row align="middle" justify="start" :gutter="2" style="margin-top: 10px;">
              <el-col :span="3" :offset="1">
                第1阶价格：
                <el-tag v-show="row.rankOne" effect="dark" type="success" style="width: 70px">{{ row.rankOne }}</el-tag>
              </el-col>
              <el-col :span="3">
                第2阶价格：
                <el-tag v-show="row.rankTwo" effect="dark" type="success" style="width: 70px">{{ row.rankTwo }}</el-tag>
              </el-col>
              <el-col :span="3">
                第3阶价格：
                <el-tag v-show="row.rankThree" effect="dark" type="success" style="width: 70px">{{ row.rankThree }}</el-tag>
              </el-col>
              <el-col :span="3">
                第4阶价格：
                <el-tag v-show="row.rankFour" effect="dark" type="success" style="width: 70px">{{ row.rankFour }}</el-tag>
              </el-col>
              <el-col :span="3">
                第5阶价格：
                <el-tag v-show="row.rankFive" effect="dark" type="success" style="width: 70px">{{ row.rankFive }}</el-tag>
              </el-col>
              <el-col :span="3">
                第6阶价格：
                <el-tag v-show="row.rankSix" effect="dark" type="success" style="width: 70px">{{ row.rankSix }}</el-tag>
              </el-col>
            </el-row>
          </template>
        </el-table-column>
        <el-table-column align="center" type="selection" width="55"/>
        <el-table-column align="left" label="品牌" prop="brand" width="180px">
          <template #header>
            <el-select
              v-model="searchParams.brand"
              clearable
              filterable
              placeholder="品牌/选择品牌"
              @change="changeGetList"
            >
              <el-option
                v-for="item in brandList"
                :key="item.recordId"
                :label="item.brand"
                :value="item.brand"
              />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column align="left" label="商品编号" prop="productNum" show-overflow-tooltip width="140px">
          <template #header>
            <el-input
              v-model="searchParams.productNum"
              clearable
              placeholder="商品编号"
              @keyup.enter.native="getList"
              @clear="changeGetList"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column align="left" label="型号" prop="modelNum" show-overflow-tooltip width="190px">
          <template #header>
            <el-input
              v-model="searchParams.modelNum"
              clearable
              placeholder="型号/输入型号回车搜索"
              @keyup.enter.native="getList"
              @clear="changeGetList"
            ></el-input>
          </template>
        </el-table-column>
        <el-table-column align="left" label="参数" prop="argument" show-overflow-tooltip width="250px">
          <template #header>
            <el-input
              v-model="searchParams.argument"
              clearable
              placeholder="参数/输入参数回车搜索"
              @keyup.enter.native="getList"
              @clear="changeGetList"
            ></el-input>
          </template>
        </el-table-column>
        <!--        <el-table-column label="第1阶数量" prop="rankNumOne" width="100px" align="left" show-overflow-tooltip />-->
        <!--        <el-table-column label="第1阶价格" prop="rankOne" width="100px" align="left" show-overflow-tooltip />-->
        <!--        <el-table-column label="第2阶数量" prop="rankNumTwo" width="100px" align="left" show-overflow-tooltip />-->
        <!--        <el-table-column label="第2阶价格" prop="rankTwo" width="100px" align="left" show-overflow-tooltip />-->
        <!--        <el-table-column label="第3阶数量" prop="rankNumThree" width="100px" align="left" show-overflow-tooltip />-->
        <!--        <el-table-column label="第3阶价格" prop="rankThree" width="100px" align="left" show-overflow-tooltip />-->
        <!--        <el-table-column label="第4阶数量" prop="rankNumFour" width="100px" align="left" show-overflow-tooltip />-->
        <!--        <el-table-column label="第4阶价格" prop="rankFour" width="100px" align="left" show-overflow-tooltip />-->
        <!--        <el-table-column label="第5阶数量" prop="rankNumFive" width="100px" align="left" show-overflow-tooltip />-->
        <!--        <el-table-column label="第5阶价格" prop="rankFive" width="100px" align="left" show-overflow-tooltip />-->
        <!--        <el-table-column label="第6阶数量" prop="rankNumSix" width="100px" align="left" show-overflow-tooltip />-->
        <!--        <el-table-column label="第6阶价格" prop="rankSix" width="100px" align="left" show-overflow-tooltip />-->
        <el-table-column align="left" label="单价" prop="unitPrice" show-overflow-tooltip width="100px" />
        <el-table-column align="left" label="出厂价" prop="factoryPrice" show-overflow-tooltip width="100px" />
        <el-table-column align="left" label="指导价" prop="guidancePrice" show-overflow-tooltip width="100px" />
        <el-table-column align="left" label="最近成交量" prop="jiangsuWarehouses" show-overflow-tooltip width="120px"/>
        <el-table-column align="left" label="广东仓" prop="guangdongGranary" show-overflow-tooltip width="110px"/>
        <el-table-column align="left" label="江苏仓" prop="jiangsuWarehouses" show-overflow-tooltip width="110px" />
        <el-table-column align="center" label="操作者" prop="operator" show-overflow-tooltip/>
        <el-table-column align="center" label="创建时间" prop="createTime" show-overflow-tooltip width="180px"/>
        <el-table-column align="center" label="操作" width="120">
          <template #default="{ row }">
            <el-tooltip content="删除" placement="top">
              <el-button v-auth="['item:product:del']" circle icon="Delete" plain type="danger" @click="handleDelete(row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <div class="h-20px"></div>
      <!-- 分页 -->
      <Pagination :getList="getList" :queryParams="searchParams" :total="total"/>

      <!-- 上传文件 -->
      <KoiDialog
        ref="koiDialogRef"
        :loading="confirmLoading"
        footerHidden
        title="上传文件"
        @koiCancel="handleCancel"
        @koiConfirm="handleConfirm"
      >
        <template #content>
          <el-upload
            ref="uploadRef"
            :action="url"
            :headers="{
              Authorization: 'Bearer ' + token
            }"
            :limit="5"
            :on-success="onSuccess"
            accept=".txt"
            class="upload-demo"
            drag
            multiple
          >
            <el-icon class="el-icon--upload">
              <upload-filled/>
            </el-icon>
            <div class="el-upload__text">
              在此处删除文件或 <em>选择文件</em>
            </div>
            <template #tip>
              <div class="el-upload__tip">
                文件的尺寸小于2M，仅支持.txt格式。
              </div>
            </template>
          </el-upload>
        </template>
      </KoiDialog>

    </KoiCard>
  </div>
</template>

<script lang="js" name="reptile" setup>
import {nextTick, reactive, ref} from "vue";
import {getToken} from "@/utils/storage.ts";
import {koiMsgBox, koiMsgError, koiMsgSuccess, koiNoticeSuccess,} from "@/utils/koi.ts";
import {brandListList, delListDetail, productExport, productList} from "@/api/tool/reptile/index.js";
import {ElMessage} from 'element-plus'

const showSearch = ref(true); // 默认显示搜索条件
// 查询参数
const searchParams = reactive({
  pageNum: 1,
  pageSize: 10,
  brand: "", // 品牌
  productNum: "", // 商品编号
  modelNum: "", //型号
  argument: "", //参数
  createTimes: null, //时间
  rank: undefined
})
const casteList = ref([
  {name: '第一阶', value: 1},
  {name: '第二阶', value: 2},
  {name: '第三阶', value: 3},
  {name: '第四阶', value: 4},
  {name: '第五阶', value: 5},
  {name: '第六阶', value: 6}
])
const createTimes = ref([])
const total = ref(0)
const tableList = ref([])
const url = import.meta.env.VITE_SERVER + "/item/product/importTxt"
const token = getToken()
const loading = ref(false)

// 列表查询
const getList = async () => {
  const query = searchParams
  if (createTimes.value.length) {
    query.createTimes = createTimes.value
  }
  loading.value = true
  const {code, data} = await productList(query)
  if (code === 200) {
    tableList.value = data.records
    total.value = data.total
  }
  loading.value = false
}

const changeGetList = () => {
  searchParams.pageNum = 1
  getList()
}

const brandList = ref([])
const getBrandListList = async () => {
  const {data} = await brandListList()
  brandList.value = data
}

// 列表重置
const resetSearch = () => {
  Object.assign(searchParams, {
    pageNum: 1,
    pageSize: 10,
    brand: "", // 品牌
    productNum: "", // 商品编号
    modelNum: "", //型号
    argument: "", //参数
    createTimes: null, //时间
    rank: undefined
  })
  createTimes.value = []
  getList()
}

const confirmLoading = ref(false);
const koiDialogRef = ref()
const handleConfirm = () => {
  koiDialogRef.value.koiOpen();
}
const handleCancel = () => {
  koiDialogRef.value.koiQuickClose();
}
const uploadRef = ref()

const uploadFile = () => {
  nextTick(async () => {
    uploadRef.value?.clearFiles();
  })
  koiDialogRef.value.koiOpen();
}
const onSuccess = (res) => {
  if (res.code === 200) {
    koiNoticeSuccess('上传成功')
    getList()
    getBrandListList()
    // koiDialogRef.value.koiQuickClose();
  } else {
    ElMessage({
      dangerouslyUseHTMLString: true,
      type: 'error',
      message: res.msg
    })
  }
  // uploadRef.value?.clearFiles();
}

// 导出
const handleExport = async () => {
  const query = searchParams
  if (createTimes.value.length) {
    query.createTimes = createTimes.value
  }
  koiMsgBox("确定导出？")
    .then(() => {
      productExport(query).then(res => {
        koiNoticeSuccess('操作成功，请去异步任务下载文件', '温馨提示', 2000)
      })
    });
}

const ids = ref([]); // 选择数组
const multiple = ref(true); // 非多个禁用
/** 是否多选 */
const handleSelectionChange = (selection) => {
  ids.value = selection.map((item) => item.recordId);
  multiple.value = !selection.length; // 多选
};
const handleDelete = (row) => {
  const delIds = [{
    id: row.recordId,
    name: row.operator || ''
  }]
  koiMsgBox("您确认需要删除么？")
    .then(async () => {
      confirmDel(delIds)
    })
    .catch(() => {
      koiMsgError("已取消");
    });
}
// 批量删除
const handleBatchDelete = () => {
  const delIds = []
  ids.value.map(v => {
    delIds.push({
      id: v,
      name: v.operator || ''
    })
  })
  koiMsgBox("您确认需要删除么？")
    .then(async () => {
      confirmDel(delIds)
    })
    .catch(() => {
      koiMsgError("已取消");
    });
}
// 确认删除
const confirmDel = async (ids) => {
  const delId = {
    delList: ids
  }
  const res = await delListDetail(delId)
  if (res.code === 200) {
    koiMsgSuccess('删除成功')
    getList()
  } else {
    koiMsgError(res.msg)
  }
}

getList()
getBrandListList()

</script>

<style lang="scss" scoped>

</style>
