<template>
  <a-card
    title="续费明细"
    :bordered="false"
  >
    <template #extra>
      <a-button @click="addRecord">添加</a-button>
    </template>
    <div class="content">
      <table
        class="ele-table ele-table-border ele-table-stripe ele-table-medium"
      >
        <thead>
          <tr>
            <th>开始时间</th>
            <th>到期时间</th>
            <th>续费金额</th>
            <th>缴费状态</th>
            <th width="320">描述</th>
            <th width="180">附件</th>
            <th style="text-align: center">操作人</th>
          </tr>
        </thead>
        <tr v-for="(item, index) in list" :key="index">
          <td>
            <template v-if="item.editStatus">
              <a-date-picker
                placeholder="开始日期"
                value-format="YYYY-MM-DD"
                v-model:value="item.startTime"
              />
            </template>
            <template v-else>
              {{ toDateString(item.startTime, 'yyyy-MM-dd') }}
            </template>
          </td>
          <td>
            <template v-if="item.editStatus">
              <a-date-picker
                placeholder="结束日期"
                value-format="YYYY-MM-DD"
                v-model:value="item.endTime"
              />
            </template>
            <template v-else>
              {{ toDateString(item.endTime, 'yyyy-MM-dd') }}
            </template>
          </td>
          <td>
            <template v-if="item.editStatus">
              <a-input-number
                  :min="0"
                  :max="999999"
                  class="ele-fluid"
                  placeholder="请输入续费金额"
                  v-model:value="item.money"
              />
            </template>
            <template v-else> ￥{{ item.money }} </template>
          </td>
          <td>
            <template v-if="item.editStatus">
              <a-select placeholder="请选择" v-model:value="item.status">
                <a-select-option :value="1">已缴费</a-select-option>
                <a-select-option :value="0">未缴费</a-select-option>
              </a-select>
            </template>
            <template v-else>
              <span v-if="item.status == 1">已缴费</span>
              <span v-if="item.status == 0">未缴费</span>
            </template>
          </td>
          <td>
            <template v-if="item.editStatus">
              <a-input
                class="ele-fluid"
                placeholder="请输入描述内容"
                v-model:value="item.comments"
              />
            </template>
            <template v-else>
              <div class="comments">{{ item.comments }}</div>
            </template>
          </td>
          <td>
            <a-upload
              v-if="item.editStatus"
              v-model:file-list="item.files"
              class="upload-list-inline"
              :maxCount="1"
              list-type="picture"
              :before-upload="beforeUpload"
            >
              <a-button>
                上传附件
              </a-button>
            </a-upload>
            <div v-else class="files">
              <a-upload
                  disabled
                  v-model:file-list="item.files"
                  class="upload-list-inline"
              >
              </a-upload>
            </div>
          </td>
          <td style="text-align: center">
            <template v-if="!item.editStatus">
              <a-space>
                {{ item.nickname }}
                <a-popconfirm title="确定要删除此记录吗？" v-if="hasRole('superAdmin')" @confirm="removeRel(index)">
                  <a class="ele-text-info">删除</a>
                </a-popconfirm>
              </a-space>
            </template>
            <template v-else>
              <a-space>
                <a @click="save(item, index)">保存</a>
                <a-divider type="vertical" />
                <a-popconfirm title="确定要删除此记录吗？" @confirm="remove(index)">
                  <a class="ele-text-info">删除</a>
                </a-popconfirm>
              </a-space>
            </template>
          </td>
        </tr>
      </table>
    </div>
  </a-card>
</template>

<script setup lang="ts">
  import { hasRole } from '@/utils/permission';
  import { ref, watch } from 'vue';
  import { addAppRenew, pageAppRenew, removeAppRenew, updateAppRenew } from "@/api/oa/app/renew";
  import { AppRenew } from '@/api/oa/app/renew/model';
  import { useUserStore } from '@/store/modules/user';
  import { message } from 'ant-design-vue';
  import { toDateString } from 'ele-admin-pro';
  import { ItemType } from "ele-admin-pro/es/ele-image-upload/types";
  import { uploadOss } from "@/api/system/file";
  import { isImage } from "@/utils/common";
  import { UploadOutlined } from "@ant-design/icons-vue";
  import rect from "zrender/src/graphic/shape/Rect";

  const props = defineProps<{
    editStatus?: boolean;
    appId?: number;
    companyId?: number;
  }>();

  const emit = defineEmits<{
    (e: 'done'): void;
    (e: 'update:visible', visible: boolean): void;
  }>();

  interface fileItem {
    uid?: number,
    url?: string,
    name?: string,
    status?: string | "done"
  }

  const userStore = useUserStore();
  const list = ref<AppRenew[]>([]);
  const files = ref<fileItem[]>([]);
  const showUploadBtn = ref(false);

  const addRecord = () => {
    list.value.unshift({
      appRenewId: undefined,
      money: undefined,
      comments: undefined,
      startTime: undefined,
      endTime: undefined,
      nickname: undefined,
      status: 1,
      images: undefined,
      files: undefined,
      editStatus: true
    });
  };

  // 文件上传事件
  const beforeUpload = (file: File) => {
    const item: ItemType = {
      file,
      uid: (file as any).uid,
      name: file.name
    }
    if (!file.type.startsWith("image")) {
      if (file.size / 1024 / 1024 > 100) {
        message.error("大小不能超过 100MB");
        return;
      }
    }
    onUpload(item);
    return false;
  };

  const onUpload = (d: ItemType) => {
    uploadOss(<File>d.file)
      .then((result) => {
        files.value.push({
          uid: result.id,
          url: result.path,
          name: isImage(result.path) ? 'image' : result.name,
          status: "done"
        });
        message.success("上传成功");
      })
      .catch((e) => {
        message.error(e.message);
      });
  };

  /* 更新visible */
  const updateVisible = (value: boolean) => {
    emit('update:visible', value);
  };

  const remove = (index: number) => {
    list.value.splice(index, 1);
  };

  const removeRel = (index: number) => {
    removeAppRenew(list.value[index].appRenewId).then(() => {
      list.value.splice(index, 1);
      message.success('删除成功')
    })
  }

  const openEdit = (index: number) => {
    list.value[index].editStatus = true
  }

  const save = (item: AppRenew, index: number) => {

    item.appId = props.appId;
    item.companyId = props.companyId;
    item.startTime = item.startTime ? item.startTime + ' 00:00:00' : '';
    item.endTime = item.endTime ? item.endTime + ' 23:59:59' : '';
    item.nickname = userStore.info?.nickname;
    item.userId = userStore.info?.userId;
    if (item.money == undefined || item.money == 0) {
      message.error('请填写金额');
      return false;
    }
    if(files.value && files.value.length > 0){
      item.images = JSON.stringify(files.value)
    }
    list.value[index].editStatus = false;
    addAppRenew(item).then(() => {
      message.success('保存成功');
      reload();
    });
    // if (item.appRenewId) {
    //   if(item.images.length > 0){
    //     list.value[index].images = JSON.parse(list.value[index].images)
    //   }
    //   updateAppRenew(item).then(() => {
    //     message.success('更新成功');
    //   })
    // }else {
    //   addAppRenew(item).then(() => {
    //     message.success('保存成功');
    //   });
    // }

  };

  const reload = () => {
    pageAppRenew({ appId: props.appId }).then((res) => {
      files.value = [];
      if (res?.list) {
        list.value = res?.list.map((d) => {
          d.editStatus = false;
          if(d.images){
            d.files = JSON.parse(d.images);
          }else{
            d.files = [];
          }
          return d;
        });
      }
    });
  };

  watch(
    () => props.appId,
    (options) => {
      if (options) {
        reload();
      }
    },
    {
      immediate: true
    }
  );
</script>

<style scoped lang="less"></style>
