<template>
  <!-- 添加或修改菜单对话框 -->
  <el-dialog title="个税信息" v-model="visible" width="800px" append-to-body draggable @close="close"
    :close-on-click-modal="false">
    <div v-loading="loading">
      <div style="padding: 8px 24px 16px 24px">
        <el-form size="small" label-width="110px">
          <el-row :gutter="30">
            <el-col :span="24">
              <el-form-item label="客户名称">
                <div>{{ currentMember }}</div>
              </el-form-item>
              <el-form-item label="所属月份">
                <!-- <div>{{ year }}-{{ month }}</div> -->
                <el-date-picker v-model="currentMonth" type="month" placeholder="请选择时间" format="YYYY-MM"
                  @change="changeMonthHandle" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-divider />
            </el-col>
            <el-col :span="12">
              <el-form-item label="个税金额">
                <el-input-number v-if="!isView" placeholder="个税金额" v-model="emptyForm.amount" :precision="2" style="

                      display: flex;
                      align-items: center;
                      justify-content: center;
                    " :controls="false" @keypress.enter.prevent />
                <div v-else>{{ rowNum(emptyForm.amount) }}</div>
              </el-form-item>
            </el-col>

            <el-col :span="12">
              <el-form-item label="备注:">
                <el-input v-if="!isView" type="textarea" rows="2" maxlength="200" show-word-limit
                  v-model="emptyForm.remark" />
                <span v-else>{{ emptyForm.remark }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <div class="details-btns-container">
                <el-form-item label="凭证文件" prop="evidenceFile" required>
                  <dragUpload :accept="accept" style="width:100%" @file="upload"
                    v-if="emptyForm.evidenceFile == null || emptyForm.evidenceFile == ''" />
                  <img v-else style="height: 148px; width: 148px" :src="`${baseUrl}/${emptyForm.evidenceFile}`"
                    class="avatar" @click="openEvidience('evidenceFile')" />
                  <div v-if="!isView|| emptyForm.status !== 3">
                    <el-icon :size="20" v-if="emptyForm.evidenceFile !== '' ||emptyForm.evidenceFile == null "
                      @click="emptyForm.evidenceFile = ''" class="delete-button">
                      <Delete />
                    </el-icon>
                  </div>
                  <div v-else>
                  </div>
                  <!-- <el-upload

                      v-if="!isView"
                      action="#"
                      :http-request="upload"
                      :with-credentials="true"
                      list-type="picture-card"
                      :show-file-list="false"
                      multiple
                    >
                      <img
                        v-if="
                          emptyForm.evidenceFile != null &&
                          emptyForm.evidenceFile !== ''
                        "
                        style="height: 148px; width: 148px"
                        :src="`${baseUrl}/${emptyForm.evidenceFile}`"
                        class="avatar"
                      />
                      <i v-else class="el-icon-plus avatar-uploader-icon" />
                    </el-upload> -->
                  <!-- <img
                      v-else-if="
                        emptyForm.evidenceFile != null &&
                        emptyForm.evidenceFile !== ''
                      "
                      style="height: 148px; width: 148px"
                      :src="`${baseUrl}/${emptyForm.evidenceFile}`"
                      class="avatar"
                      @click="openEvidience('evidenceFile')"
                    /> -->
                </el-form-item>
                <!-- 删除按钮 -->

              </div>
            </el-col>
            <el-col :span="24" style="padding: 15px 15px 16px 15px">
              <div class="details-btns-container">
                <el-form-item label="报表文件" prop="reportFile" required>
                  <el-upload v-if="!isView || emptyForm.status !== 3" action="#" :http-request="uploadextFile"
                    :with-credentials="true" :show-file-list="false" multiple>
                    <el-button size="small" type="primary" icon="Upload">点击上传</el-button>
                  </el-upload>
                </el-form-item>
              </div>
              <div class="details-body" style="height: 100px">
                <el-table ref="filesTable" :data="reportFiles" size="small" height="100%" border
                  header-row-class-name="list-header-row">
                  <el-table-column label="文件名" prop="fileName" align="center">
                    <template #default="scope">
                      <el-button @click="openEvidenceFile(scope.row)" type="primary" link>
                        {{ scope.row.fileName }}
                      </el-button>
                    </template>
                  </el-table-column>
                  <el-table-column v-if="!isView || emptyForm.status !== 3" label="操作" width="50" align="center">
                    <template #default="scope">
                      <el-button size="small" link type="danger" @click="handleDelFile(scope.$index)">删除</el-button>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-col>
          </el-row>
        </el-form>


        <div class="form-btns-container" style="height: 40px" v-if="!stopUseBack">
          <el-button size="small" icon="close" v-if="!isView || emptyForm.status !== 3"
            style="float: right; margin-left: 12px; margin-right: 12px" @click="close">
            取消
          </el-button>
      
            <el-button type="primary" size="small" icon="Finished"  v-if="!isView || emptyForm.status !== 3"
              v-hasPermi="['business:individualIncomeTaxDetail:saveDetail']" style="float: right" @click="handleSave">
              保存
            </el-button>
          <el-button v-hasPermi="['business:individualIncomeTaxDetail:deductionTurnBack']" icon="back" type="warning"
            size="small" style="float: right;" :disabled="(emptyForm == null || emptyForm.status !== 3)  "
            @click="turnBack(emptyForm)">
            退回
          </el-button>
        </div>
      </div>


    </div>
  </el-dialog>
</template>


<script setup>
  const { proxy } = getCurrentInstance();
  import { rowNum } from "@/utils/index";

  /** 父组件传参 */
  const props = defineProps({
    getList: {
      type: Function,
      default: () => { },
    },
  });
  const { getList } = toRefs(props);
  /** 字典数组区 */
  const { develop_type } = proxy.useDict("develop_type");
  /** 表单抽屉 页变量 */
  const title = ref("");
  const loading = ref(false);
  const multiple = ref(true);
  const visible = ref(false);
  const editStatus = ref(false);
  const isFullscreen = ref(false);
  const addDetailNum = ref(1);
  const isAdd = ref(false);
  const isView = ref(false);
  const mainInfo = ref({});
  const monthInfo = ref({});
  const currentMember = ref({});
  const year = ref({});
  const month = ref({});
  const cities = ref([]);
  const districts = ref([]);
  const fileList = ref([]);
  const reportFiles = ref([]);
  const sourceCategories = ref([]);
  const tenantId = ref(0);
  const addType = ref(1);
  const stopUseBack = ref(false);
  const currentMonth = ref(
    proxy.moment().subtract(1, "month").format("YYYY-MM-01")
  );
  const emptyForm = ref({
    financialIndividualIncomeTaxId: null,
    companyId: null,
    parentId: "0",
    name: "",
    code: "",
    receiveDate: proxy.moment().format("YYYY-MM-DD HH:mm:ss"),
    receiveDateRange: proxy.moment().format("YYYY-MM-DD"),
    receiveTimeRange: "08:00:00",
    evidenceFile: "",
    reportFile: "",
    originalFileName: "",
    status: null,
    fileName: "",
    fileList: [],
    year: "",
    month: "",
    reportFiles: [],
    workOrderId: null,
  });

  watch(addType, (value) => {
    switch (value) {
      case "1":
        break;
      case "2":
        break;
      default:
        break;
    }
  });

  import { uploadFile } from "@/api/tool/file";
  import {
    addIndividualIncomeTaxDetail,
    updateIndividualIncomeTaxDetail,
    getDetail,
    getInfo,
  } from "@/api/business/production/detail";
  import dragUpload from "@/components/dragUpload"
  import { ref } from "vue";
  // import { de } from "element-plus/es/locale";
  // import { de } from "element-plus/es/locale";
  const baseUrl = import.meta.env.VITE_APP_BASE_API;

  const followQuery = ref({});

  /***********************  表单页方法 ****************************/

  /** 抽屉打开 */
  function open(id, mainRow, monthItem) {
    visible.value = true;
    tenantId.value = mainRow.tenantId;
    mainInfo.value = mainRow;
    monthInfo.value = monthItem;
    console.log("id", id);
    currentMonth.value = proxy.moment().subtract(1, "month").format("YYYY-MM-01")
    if (id == 0) {
      isAdd.value = true;
      isView.value = false;
      loadData(id);
    } else if (id == null || mainRow.detail.status == 3) {
      isView.value = true;
      console.log("查看");
      getInfoId(id);
    } else {
      console.log("修改");
      isView.value = false;
      isAdd.value = false;
      getInfoId(id);
    }
    getDetail(queryParams.value).then((response) => {
      detailList.value = response.rows;
      total.value = response.total;
      loading.value = false;
    });
  }

  function getInfoId(id) {
    console.log("id", mainInfo.value);
    getInfo(mainInfo.value.id, monthInfo.value.year, monthInfo.value.month).then((response) => {
      console.log("response", response);
      mainInfo.value.detail = response.data;
      reportFiles.value = response.data.reportFiles;
      emptyForm.value = response.data;
      loadData(id);
    });
  }

  function loadData(id) {
    console.log("monthInfo", mainInfo.value);
    year.value = monthInfo.value.year;
    month.value = monthInfo.value.month;
    currentMember.value = mainInfo.value.companyName;
    emptyForm.value.financialIndividualIncomeTaxId = mainInfo.value.id;
    emptyForm.value.workOrderId = mainInfo.value.workOrderId;
    if (!isAdd.value) {
      reportFiles.value = mainInfo.value.detail.reportFiles;
      if (mainInfo.value.detail.evidenceFile != "") {
        const file = {};
        file.url = mainInfo.value.evidenceFile;
        file.fileUrl = mainInfo.value.detail.evidenceFile;
        file.originalFileName = mainInfo.value.detail.originalFileName;
        fileList.value.push(file);
        emptyForm.value.evidenceFile = mainInfo.value.detail.evidenceFile;
        emptyForm.value.originalFileName = mainInfo.value.detail.originalFileName;
        emptyForm.value.fileName = mainInfo.value.detail.fileName;
      }
    }
  }
  /** 退回按钮操作 */
  function turnBack(row) {
    loading.value = true
    emptyForm.value.status = 1;
    // emptyForm.value.workOrderId = workOrderId;
    emptyForm.value.year = proxy.moment(currentMonth.value).format("YYYY");
    emptyForm.value.month = proxy.moment(currentMonth.value).format("MM");
    console.log(emptyForm);
    updateIndividualIncomeTaxDetail(emptyForm.value);
    loading.value = false;
    getList.value();
    visible.value = false;
  }
  function changeMonthHandle(parentId) {
    isView.value = true
    const nowDate = ref(
      proxy.moment().subtract(1, "month").format("YYYY-MM-01")
    );
    let nowyear = proxy.moment(nowDate.value).format("YYYY");
    let nowmonth = proxy.moment(nowDate.value).format("MM");
    const year = proxy.moment(currentMonth.value).format("YYYY");
    const month = proxy.moment(currentMonth.value).format("MM");

    if (nowyear + nowmonth == year + month) {
      if(emptyForm.value.status === 3 ){
        isView.value =true
      }else{
        isView.value =false
      }
      stopUseBack.value = false
    } else {
      stopUseBack.value = true
    }
    getInfo(mainInfo.value.id, year, month).then((response) => {
      mainInfo.value.detail = response.data;
      emptyForm.value = response.data;
      loadData(parentId);
    });
  }
  /** 上传报表附件 */
  function uploadextFile(param) {
    const formData = new FormData();
    formData.append("file", param.file);
    uploadFile(formData).then((res) => {
      if (res.code === 200) {
        const file = {};
        file.fileName = res.newFileName;
        file.fileUrl = res.fileName;
        file.originalFileName = res.originalFilename;
        file.fileType = param.file.type;
        file.fileSize = param.file.size;
        file.tenantId = tenantId.value;
        reportFiles.value.push(file);
        console.log(reportFiles.value);
        console.log("成功", res);
        emptyForm.value.reportFile = file.fileUrl;
        console.log("文件", reportFiles.value);
      }
    });
  }

  function openEvidience() {
    window.open(`${baseUrl}${emptyForm.value.evidenceFile}`);
  }

  function handleDelFile(index) {
    reportFiles.value.splice(index, 1);
  }

  /**  保存 */
  function handleSave() {

    if (
      emptyForm.value.evidenceFile == null ||
      emptyForm.value.evidenceFile === ""
    ) {
      proxy.$message.error("请上传凭证");
      return;
    }

    if (!reportFiles.value.length > 0) {
      proxy.$message.error("请上传报表");
      return;
    }
    loading.value = true
    emptyForm.value.files = fileList.value;
    // emptyForm.value.year = year.value;
    // emptyForm.value.month = month.value;
    emptyForm.value.year = proxy.moment(currentMonth.value).format("YYYY");
    emptyForm.value.month = proxy.moment(currentMonth.value).format("MM");
    emptyForm.value.status = 3;
    emptyForm.value.reportFiles = reportFiles.value;
    if (isAdd.value) {
      emptyForm.value.companyId = mainInfo.value.companyId;
      addIndividualIncomeTaxDetail(emptyForm.value)
        .then((res) => {
          console.log(res);
          proxy.$modal.msgSuccess("保存成功!");
          visible.value = false;

          getList.value();
        })
        .catch((err) => {
          proxy.$modal.lmsgError(err);
          console.log(err);
        }).finally(() => {
          loading.value = false
        });
    } else {
      mainInfo.value.detail.status = 3;
      mainInfo.value.detail.fileName = emptyForm.value.fileName;
      mainInfo.value.detail.originalFileName = emptyForm.value.originalFileName;
      mainInfo.value.detail.evidenceFile = emptyForm.value.evidenceFile;
      console.log("保存修改");
      console.log(mainInfo.value.detail);
      addIndividualIncomeTaxDetail(mainInfo.value.detail)
        .then((res) => {
          console.log(res);
          proxy.$modal.msgSuccess("保存成功!");
          visible.value = false;

          getList.value();
        })
        .catch((err) => {
          proxy.$modal.$modalMsgError(err);
          console.log(err);
        }).finally(() => {
          loading.value = false
        });;
    }
  }

  /** 文件上传 */
  function upload(param) {

    const formData = new FormData();
    formData.append("file", param);
    uploadFile(formData).then((res) => {
      if (res.code === 200) {
        const file = {};
        file.fileName = res.newFileName;
        file.url = res.fileName;
        file.originalFileName = res.originalFilename;
        file.fileUrl = res.fileName;
        fileList.value.push(file);
        emptyForm.value.evidenceFile = file.fileUrl;
        emptyForm.value.originalFileName = res.originalFilename;
        emptyForm.value.fileName = res.newFileName;
      }
    });
  }

  function uploadSuccess(res, field) {
    if (res.code === 200) {
      form[field] = res.data.fileUrl;
    } else proxy.$modal.msg.error("文件上传失败");
  }

  /** 关闭 */
  function close() {
    emptyForm.value = {};
    reportFiles.value = [];
    getList.value();
    visible.value = false;
  }

  function openEvidenceFile(row) {
    // console.log(`${baseUrl}${row.fileUrl}`);
    window.open(`${baseUrl}${row.fileUrl}`);
  }

  // 暴露给父组件的方法
  defineExpose({
    open,
  });
</script>

<style scoped>
  .delete-button {
    margin-left: 20px;
    cursor: pointer;
  }
</style>