<template>
  <div class="koi-flex">
    <KoiCard>
      <el-row>
        <el-col :span="9">
          <el-form :model="form" label-width="auto">
            <el-form-item label="报刊日期">
              <el-date-picker
                v-model="form.datetime"
                type="date"
                value-format="YYYY-MM-DD"
                placeholder="选择报刊日期"
                style="width: 100%"
              ></el-date-picker>
            </el-form-item>
<!--            <el-form-item label="报刊类型">-->
<!--              <el-select v-model="form.type_id" placeholder="选择报刊类型">-->
<!--                <el-option v-for="item in typeList" :label="item.type" :value="item.id"/>-->
<!--              </el-select>-->
<!--            </el-form-item>-->
            <el-form-item>
              <el-button @click="addBlack" class="mt-2">新增版面</el-button>
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-col :span="8" v-for="(item,index) in backArr">
          <el-card class="m-b-5" shadow="hover">
            <template #header>
              <div class="flex justify-between items-center">
                <div>{{ item.bm_name ? item.bm_name : '版面' }}</div>
                <div>
                  <el-space wrap :size="30">
                    <!--                    <el-icon class="cursor-pointer" @click="left_right('l',index)">-->
                    <!--                      <ArrowLeftBold/>-->
                    <!--                    </el-icon>-->
                    <!--                    <el-icon class="cursor-pointer" @click="left_right('r',index)">-->
                    <!--                      <ArrowRightBold/>-->
                    <!--                    </el-icon>-->
                    <el-icon class="cursor-pointer" @click="del(index)">
                      <DeleteFilled/>
                    </el-icon>
                  </el-space>
                </div>
              </div>
            </template>
            <el-form :model="form" label-width="auto">
              <el-form-item label="版面名称">
                <el-input v-model="item.bm_name" placeholder="输入版面名称"/>
              </el-form-item>
              <el-form-item label="版面排序">
                <el-input @blur="addSort" type="number" v-model="item.weight" placeholder="输入版面排序"/>
              </el-form-item>
              <el-form-item label="版面PDF">
                <KoiUploadFiles :fileList="item.pdf" acceptType=".pdf" @update:fileList="(file) => updateFileList(file, index)"
                                @fileSuccess="(file) => getFileList(file, index)">
                  <template #tip>PDF最大为 10M</template>
                </KoiUploadFiles>
              </el-form-item>
              <el-form-item label="版面图片" prop="avatar">
                <KoiUploadImage :imageUrl="item.bm_img" @update:imageUrl="(file) => getImgList(file, index)" width="150px"
                                height="150px">
                  <template #content>
                    <el-icon>
                      <Picture/>
                    </el-icon>
                    <span>请上传版面图片</span>
                  </template>
                  <template #tip>图片最大为 3M</template>
                </KoiUploadImage>
              </el-form-item>
            </el-form>
          </el-card>
        </el-col>
      </el-row>
      <div class="text-center p-10">
        <el-button type="primary" class="w-80" plain @click="handleMineSave">保存报刊</el-button>
      </div>
    </KoiCard>
  </div>
</template>
<script setup lang="ts">
import {nextTick, ref, reactive, onMounted} from "vue";
import {bmAdd, getList} from "@/api/system/post/index.ts";
import {
  koiMsgSuccess,
  koiNoticeSuccess,
  koiNoticeError,
  koiMsgError,
  koiMsgWarning,
  koiMsgBox,
  koiMsgInfo
} from "@/utils/koi.ts";
import useTabsStore from "@/stores/modules/tabs.ts";
import {useRoute, useRouter} from "vue-router";
import { ElLoading } from 'element-plus'
const route = useRoute();
const router = useRouter();
const tabsStore = useTabsStore();
const getFileList = (d, index) => {
  console.log(d);
  console.log(index);
  backArr.value[index].bm_pdf = d.fullurl;
}
const updateFileList = (d, index) => {
  console.log(d);
  console.log(index);
  backArr.value[index].bm_pdf = d.fullurl ? d.fullurl : '';
}
const getImgList = (d, index) => {
  console.log(d);
  console.log(index);
  backArr.value[index].bm_img = d;
}

const backArr = ref([
  {bm_name: '', bm_img: '', bm_pdf: '', weight: 0, pdf: []}
]);
const form = reactive({
  datetime: "",
  type_id: ""
});
const addBlack = () => {
  // 找到当前 backArr 数组中最大的 weight 值
  const maxWeight = Math.max(...backArr.value.map(item => item.weight), 0);

  // 添加新的版面，weight 设置为 maxWeight + 1
  backArr.value.push({bm_name: '', bm_img: '', bm_pdf: '', weight: maxWeight + 1, pdf: []});
}
const addSort = () => {
  //根据数组中的weight排序数组
  backArr.value.sort((a, b) => a.weight - b.weight);
}
onMounted(() => {
  //getTypelist();
})
const typeList = ref();
const getTypelist = async () => {
  try {
    const res: any = await getList([]);
    typeList.value = res.data;
  } catch (error) {
    console.log(error);
    koiNoticeError("数据查询失败，请刷新重试!");
  }
}
const handleMineSave = async () => {

  if (form.datetime == '') {
    koiMsgError('请选择报纸日期');
    return;
  }
  // if (form.type_id == '' || form.type_id == null) {
  //   koiMsgError('请选择报纸类别');
  //   return;
  // }
  for (let i = 0; i < backArr.value.length; i++) {
    if (backArr.value[i].bm_name == '' || backArr.value[i].bm_img == '' || backArr.value[i].bm_pdf == '') {
      koiMsgError('请完善版面[' + (i + 1) + ']信息');
      return;
    }
  }
  const data = {date: form, bm: backArr.value};
  const loading = ElLoading.service({
    lock: true,
    text: '保存中...',
    background: 'rgba(0, 0, 0, 0.1)',
  })
  try {
    await bmAdd(data);
    koiNoticeSuccess("保存成功!");
    loading.close();
    tabsStore.removeTab(route.fullPath);
    router.push('/paper/list');
  } catch (error) {
    console.log(error);
    koiNoticeError("保存失败，请刷新重试!");
  }
}
const left_right = (type, index) => {
  const arr = backArr.value;
  if (type === 'l' && index > 0) {
    // 向左移动
    [arr[index], arr[index - 1]] = [arr[index - 1], arr[index]];
  } else if (type === 'r' && index < arr.length - 1) {
    // 向右移动
    [arr[index], arr[index + 1]] = [arr[index + 1], arr[index]];
  }
  // 重置下标数组（这里假设重置下标数组的意思是重新排序）
  backArr.value = [...arr];
};
const del = (index) => {
  const arr = backArr.value;
  if (arr.length <= 1) {
    koiMsgError('至少保留一个版面');
    return;
  }
  if (index >= 0 && index < arr.length) {
    arr.splice(index, 1);
  }
  // 重置下标数组（这里假设重置下标数组的意思是重新排序或更新）
  backArr.value = [...arr];
};
</script>
<style scoped lang="scss">

</style>
