<template>
  <!-- 添加或修改菜单对话框 -->
  <el-dialog title="报税信息" v-model="visible" width="800px" append-to-body draggable :close-on-click-modal="false"
    @close="close">
    <div v-loading="loading">
      <div>
        <div style="padding: 8px 24px 16px 24px">
          <el-form size="small" label-width="130px">
            <el-row :gutter="30">
              <el-col :span="12">
                <el-form-item label="客户名称">
                  <div>{{ currentMember }}</div>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <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="12">
                <el-form-item label="可弥补之前年度亏损">
                  <el-input-number v-if="(editStatus && !isView)|| emptyForm.status !== 3" size="small"
                    placeholder="可弥补之前年度亏损" v-model="emptyForm.previousAnnualLosses" style="width: 120%" :precision="2"
                    :controls="false" />
                  <div v-else>
                    {{ rowNum(emptyForm.previousAnnualLosses ? null : 0.0) }}
                    <el-button link type="primary" icon="Edit" size="small" style="margin-left: 20px"
                      v-if="!isView || emptyForm.status !== 3" @click="editStatus = true" />
                  </div>
                  <template v-if="isView">
                    <span>{{ rowNum(emptyForm.previousAnnualLosses) }}</span>
                  </template>
                </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 || emptyForm.status !== 3" placeholder="增值税"
                    v-model="emptyForm.valueAddedTax" style="
                    display: flex;
                    align-items: center;
                    justify-content: center;
                  " @change="taxChangeHandler" :controls="false" :precision="2" />
                  <div v-else>{{ rowNum(emptyForm.valueAddedTax) }}</div>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="城建税">
                  <el-input-number v-if="!isView || emptyForm.status !== 3" placeholder="城建税"
                    v-model="emptyForm.cityConstructTax" style="
                    display: flex;
                    align-items: center;
                    justify-content: center;
                  " @change="taxChangeHandler" :controls="false" :precision="2" />
                  <div v-else>{{ rowNum(emptyForm.cityConstructTax) }}</div>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="教育费附加">
                  <el-input-number v-if="!isView || emptyForm.status !== 3" placeholder="教育费附加"
                    v-model="emptyForm.additionsTaxOfEducation" style="
                    display: flex;
                    align-items: center;
                    justify-content: center;
                  " @change="taxChangeHandler" :precision="2" :controls="false" />
                  <div v-else>
                    {{ rowNum(emptyForm.additionsTaxOfEducation) }}
                  </div>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="地方教育费附加">
                  <el-input-number v-if="!isView || emptyForm.status !== 3" placeholder="地方教育费附加"
                    v-model="emptyForm.ladditionsTaxOfEducation" style="
                    display: flex;
                    align-items: center;
                    justify-content: center;
                  " @change="taxChangeHandler" :precision="2" :controls="false" />
                  <div v-else>
                    {{ rowNum(emptyForm.ladditionsTaxOfEducation) }}
                  </div>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="企业所得税">
                  <el-input-number v-if="!isView || emptyForm.status !== 3" placeholder="企业所得税"
                    v-model="emptyForm.businessIncomeTax" style="
                    display: flex;
                    align-items: center;
                    justify-content: center;
                  " @change="taxChangeHandler" :precision="2" :controls="false" />
                  <div v-else>{{ rowNum(emptyForm.businessIncomeTax) }}</div>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="印花税">
                  <el-input-number v-if="!isView || emptyForm.status !== 3" placeholder="印花税"
                    v-model="emptyForm.stampTax" style="
                    display: flex;
                    align-items: center;
                    justify-content: center;
                  " @change="taxChangeHandler" :precision="2" :controls="false" />
                  <div v-else>{{ rowNum(emptyForm.stampTax) }}</div>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="文化事业建设税">
                  <el-input-number v-if="!isView || emptyForm.status !== 3" placeholder="文化事业建设税"
                    v-model="emptyForm.culturalConstructTax" style="
                    display: flex;
                    align-items: center;
                    justify-content: center;
                  " @change="taxChangeHandler" :precision="2" :controls="false" />
                  <div v-else>{{ rowNum(emptyForm.culturalConstructTax) }}</div>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="消费税">
                  <el-input-number v-if="!isView || emptyForm.status !== 3" placeholder="消费税" v-model="emptyForm.excise"
                    style="
                    display: flex;
                    align-items: center;
                    justify-content: center;
                  " @change="taxChangeHandler" :precision="2" :controls="false" />
                  <div v-else>{{ rowNum(emptyForm.excise) }}</div>
                </el-form-item>
              </el-col>

              <el-col :span="12">
                <el-form-item label="合计">
                  <div v-if="emptyForm.sumTax != 0">
                    {{ rowNum(emptyForm.sumTax) }}
                  </div>
                </el-form-item>
              </el-col>

              <el-col :span="24">
                <el-divider />
              </el-col>

              <el-col :span="12" v-if="!isView || emptyForm.status !== 3">
                <el-form-item label="备注">
                  <el-input type="textarea" rows="2" maxlength="200" show-word-limit v-model="emptyForm.content" />
                </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"
                    :file-list="files"
                    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">
                    <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-link :href="`${baseUrl}${scope.row.fileUrl}`" :underline="false" target="_blank"
                          type="primary">
                          {{ scope.row.fileName }}
                        </el-link>
                      </template>
                    </el-table-column>
                    <el-table-column label="文件类型" prop="fileType" width="100" align="center">
                      <template #default="scope">
                        <el-link :underline="false" target="_blank">
                          {{ scope.row.fileType }}
                        </el-link>
                      </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>
      </div>
      <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>
        <div  v-if="!isView || emptyForm.status !== 3" >
          <el-button type="primary" size="small" icon="Finished"
          @click="handleSave" v-hasPermi="['business:financialReportTax:saveDetail']" style="float: right">
          保存</el-button>
        </div>
        <div >
          <el-button type="warning" size="small" style="float: right;" icon="back"
          :disabled="emptyForm == null || emptyForm.status !== 3 " @click="turnBack(emptyForm)"
          v-hasPermi="['business:financialReportTaxNonZero:back']">
          退回
        </el-button>
        </div>
       
      </div>
    </div>
  </el-dialog>
</template>


<script setup>
  import { rowNum } from "@/utils/index";
  const { proxy } = getCurrentInstance();
  /** 父组件传参 */
  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 files = ref([]);
  const reportFiles = ref([]);
  const tenantId = ref(0);
  const currentMonth = ref(
    proxy.moment().subtract(1, "month").format("YYYY-MM-01")
  );
  const sourceCategories = ref([]);

  const addType = ref(1);

  const emptyForm = ref({
    id: null,
    originalFileName: "",
    fileName: "",
    financialReportTaxId: null,
    companyId: null,
    year: null,
    month: null,
    files: [],
    reportFiles: [],
    workOrderId: null,
  });
  const stopUseBack = ref(false);
  const data = reactive({
    form: {},
  });

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

  import { saveDetail, updateTax, getTax, deductionTurnBack } from "@/api/business/production/tax";
  import { uploadFile } from "@/api/tool/file";
  import dragUpload from "@/components/dragUpload"
  // import { de } from "element-plus/es/locale";
  import { ref } from "vue";

  const baseUrl = import.meta.env.VITE_APP_BASE_API;
  const parentId = ref(null);
  const { form, rules } = toRefs(data);

  const followQuery = ref({});

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

  /** 抽屉打开 */
  function open(id, mainRow, monthItem) {
    console.log("打开抽屉", id);
    visible.value = true;
    mainInfo.value = mainRow;
    monthInfo.value = monthItem;
    tenantId.value = mainRow.tenantId;
    currentMonth.value = proxy.moment().subtract(1, "month").format("YYYY-MM-01")
    parentId.value = id
    if (id == 0) {
      isAdd.value = true;
      isView.value = false;
    } else if (id == null) {
      isView.value = true;
      emptyForm.value = mainRow.detail;
    } else {
      emptyForm.value = mainRow.detail;
      isView.value = false;
      isAdd.value = false;
    }

    getTaxId(mainRow, id);
  }

  function getTaxId(mainRow, id) {
    if (mainRow.detail != null) {
      getTax(mainInfo.value.id, monthInfo.value.year, monthInfo.value.month).then((res) => {
        if (res.code === 200) {
          emptyForm.value = res.data;

          reportFiles.value = emptyForm.value.reportFiles;
          loadData(id);
        }
      });
    } else {
      loadData(id);
    }
  }
  function changeMonthHandle(parentId) {

    loading.value = true
    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
    }
    getTax(mainInfo.value.id, year, month).then((res) => {
      if (res.code === 200) {
        console.log("查询成功");
        emptyForm.value = res.data;
        reportFiles.value = emptyForm.value.reportFiles;
        loadData(parentId);
      }
    }).finally(() => {
      loading.value = false
    });
  }

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

  function loadData(id) {
    month.value = monthInfo.value.month;
    currentMember.value = mainInfo.value.companyName;
    emptyForm.value.workOrderId = mainInfo.value.workOrderId;
    year.value = monthInfo.value.year;
    emptyForm.value.financialIndividualIncomeTaxId = mainInfo.value.id;
    emptyForm.value.isZero = mainInfo.value.isZero;
    emptyForm.value.financialReportTaxId = mainInfo.value.id;
    emptyForm.value.workOrderId = mainInfo.value.workOrderId;
    if (!isAdd.value) {
      if (mainInfo.value.detail != null) {
        emptyForm.value.evidenceFile = mainInfo.value.detail.evidenceFile;
      }
    }
  }
  /** 退回按钮操作 */
  function turnBack(detail) {
    loading.value = true
    emptyForm.value.status = 1;
    emptyForm.value.year = proxy.moment(currentMonth.value).format("YYYY");
    emptyForm.value.month = proxy.moment(currentMonth.value).format("MM");
    deductionTurnBack(emptyForm.value)
      .then((res) => {
        proxy.$modal.msgSuccess("保存成功!");
        getList().value();
      })
      .catch((err) => {
        proxy.$modal.$modalMsgError(err);
        getList().value();
      });
    getList.value();
    loading.value = false;
    visible.value = false;
  }
  /** 计算税额 */
  function taxChangeHandler() {
    let amount = 0;

    amount +=
      emptyForm.value.ladditionsTaxOfEducation == null
        ? 0
        : emptyForm.value.ladditionsTaxOfEducation;
    amount +=
      emptyForm.value.valueAddedTax == null ? 0 : emptyForm.value.valueAddedTax;
    amount +=
      emptyForm.value.cityConstructTax == null
        ? 0
        : emptyForm.value.cityConstructTax;
    amount +=
      emptyForm.value.additionsTaxOfEducation == null
        ? 0
        : emptyForm.value.additionsTaxOfEducation;
    amount +=
      emptyForm.value.businessIncomeTax == null
        ? 0
        : emptyForm.value.businessIncomeTax;
    amount += emptyForm.value.stampTax == null ? 0 : emptyForm.value.stampTax;
    amount +=
      emptyForm.value.culturalConstructTax == null
        ? 0
        : emptyForm.value.culturalConstructTax;
    amount += emptyForm.value.excise == null ? 0 : emptyForm.value.excise;
    emptyForm.value.sumTax = amount;
  }

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

  /**  保存 */
  function handleSave() {
    emptyForm.value.reportFiles = reportFiles;
    if (
      emptyForm.value.evidenceFile == null ||
      emptyForm.value.evidenceFile === ""
    ) {
      proxy.$message.error("请上传凭证");
      return;
    }

    emptyForm.value.files = files.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");
    console.log("monthInfo", monthInfo.value);
    console.log("month", month.value);
    emptyForm.value.status = 3;
    console.log("保存", emptyForm.value);
    loading.value = true
    if (isAdd.value) {
      emptyForm.value.companyId = mainInfo.value.companyId;
      console.log("新增", emptyForm.value);
      saveDetail(emptyForm.value)
        .then((res) => {
          proxy.$modal.msgSuccess("保存成功!");
          visible.value = false;

          getList.value();
        })
        .catch((err) => {
          proxy.$modal.$modalMsgError(err);
          console.log(err);
        }).finally(() => {
          loading.value = false
        });
      getList.value();
    } else {
      mainInfo.value.detail.status = 3;
      saveDetail(emptyForm.value)
        .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 uploadextFile(param) {
    const formData = new FormData();
    formData.append("file", param.file);
    uploadFile(formData).then((res) => {
      if (res.code === 200) {
        console.log(res);
        const file = {};
        file.fileType =
          res.newFileName.split(".")[res.newFileName.split(".").length - 1];
        file.fileName = res.newFileName;
        file.fileUrl = res.fileName;
        file.rawFileName = res.originalFilename;
        file.fileSize = param.file.size;
        file.tenantId = tenantId.value;
        emptyForm.value.reportFile = file.fileUrl;
        reportFiles.value.push(file);
        console.log("文件", reportFiles.value);
      }
    });
  }

  /** 文件上传 */
  function upload(param) {
    const formData = new FormData();
    formData.append("file", param);
    uploadFile(formData).then((res) => {
      if (res.code === 200) {
        console.log(res);
        const file = {};
        file.fileName = res.newFileName;
        file.url = res.url;
        file.originalFileName = res.originalFilename;
        file.fileUrl = res.fileName;
        files.value.push(file);
        file.fileType = param.type;
        file.fileSize = param.size;
        emptyForm.value.evidenceFile = file.fileUrl;
      }
    });
  }

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

  function reset() {
    emptyForm.value = {
      id: null,
      originalFileName: "",
      fileName: "",
      financialReportTaxId: null,
      companyId: null,
      year: null,
      month: null,
      taxType: null,
      isZero: null,
      valueAddedTax: 0,
      cityConstructTax: 0,
      additionsTaxOfEducation: 0,
      ladditionsTaxOfEducation: 0,
      individualIncomeTax: 0,
      businessIncomeTax: 0,
      stampTax: 0,
      culturalConstructTax: 0,
      excise: 0,
      sumTax: 0,
      previousAnnualLosses: null,
      status: null,
      content: null,
      verifyContent: null,
      createTime: null,
      creatorId: null,
      updateTime: null,
      updaterId: null,
      deleted: null,
      version: null,
      evidenceFile: null,
      reportFile: null,
      verifierId: null,
      files: [],
      reportFiles: [],
    };
    handleDelFile();
  }

  /** 关闭 */
  function close() {
    visible.value = true;
    reset();
    getList.value();
    visible.value = false;
  }

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

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

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