<template>
  <!-- 添加或修改项目信息对话框 -->
  <div class="el-drawer__wrapper company-list">
      <el-drawer :title="title" v-model="visible" direction="rtl" size="100%">
        <div class="page-container form-container">
          <!-- 功能按钮区域 -->
          <div class="form-btns-container">
            <span class="title-label"><el-icon>
                <Document />
              </el-icon>
              对账单表单</span>

            <el-button v-if="editStatus" type="primary" size="small" icon="Finished" @click="submitForm">保存</el-button>
            <el-button v-else-if="form.entrustOrderStatus !== 2 && form.status !== 2" type="warning" size="small"
              icon="Edit" @click="editStatus = true"
              v-hasPermi="['business:statement:update']"
              >修改</el-button>
            <el-button v-if="form.id && editStatus" type="info"   v-hasPermi="['business:statement:update']"  size="small" icon="Close"
              @click="editStatus = false">取消修改</el-button>
            <el-button type="warning" size="small" icon="Download" @click="exportExcel" v-hasPermi="['business:statement:export']">导出</el-button>
            <el-button v-if="form.id" type="success" icon="refresh" size="small" @click="getForm">
              刷新</el-button>

            <div class="screen-btn" @click="handleScreen">
              <template v-if="!isFullscreen">
                <i class="fa fa-window-maximize" aria-hidden="true" />
                <!-- <span>全屏</span> -->
              </template>
              <template v-else>
                <i class="fa fa-window-restore" aria-hidden="true" />
                <!-- <span>还原</span> -->
              </template>
            </div>
            <div class="close-btn" @click="cancel">
              <i class="fa fa-times" aria-hidden="true" />
              <!-- <span>关闭</span> -->
            </div>
          </div>
          <el-form ref="companyRef" class="master-container" size="small" :model="form" :rules="rules"
            label-width="120px">
            <el-row :gutter="30">
              <el-col :span="6"> 结算单位：{{ form.contactCompany }} </el-col>
              <el-col :span="6"> 结算订单编号：{{ form.formNo }} </el-col>
              <el-col :span="4">
                上期余额：{{ rowNum(form.prevRemainAmount) }}
              </el-col>
              <el-col :span="4"> 本期消耗：{{ rowNum(form.amount) }} </el-col>
              <el-col :span="4">
                本期余额：{{ rowNum(form.remainAmount) }}
              </el-col>
              <el-col :span="24">
                <el-tabs v-model="activeName">
                  <el-tab-pane label="汇总" name="base" class="baseTable">
                    <table class="header" cellspacing="0" cellpadding="0" style="table-layout: fixed"
                      v-loading="loading">
                      <tbody>
                        <tr class=" bg-white-color">
                      <td :colspan="1" style="width: 100px">自然月</td>
                      <td :colspan="2" style="width: 200px">项目分类</td>
                      <td :colspan="1" style="width: 100px">
                        客户数量（单位：户）
                      </td>
                      <td :colspan="1" style="width: 100px">
                        单价（单位：元）
                      </td>
                      <td :colspan="1" style="width: 100px">
                        小计（单位：元）
                      </td>
                      <td :colspan="1" style="width: 100px">优惠后单价</td>
                      <td :colspan="1" style="width: 100px">优惠后金额</td>
                      <td :colspan="1" style="width: 100px">减免金额</td>
                      <td :colspan="1" style="width: 100px">实际支付</td>
                      <td :colspan="2" class="tdLast" style="width: 300px">
                        说明
                      </td>
                      </tr>
                      <tr class="bg-white-color" v-for="(item, index) in form.collect" :key="index">
                        <td :colspan="1" v-if="index === 0" :rowspan="form.collect.length">
                          <!-- {{ item.year }}年{{ item.month}}月 -->
                          {{ form.startMonth }} - {{ form.endMonth }}
                        </td>
                        <td :colspan="1">{{ item.taskType }}</td>
                        <td :colspan="1">
                          {{
                          item.taskType === "代理记账"
                          ? item.annualIncome
                          : item.taskType === "社保代缴" ||
                          item.taskType === "公积金代缴"
                          ? item.haveChanged === 1
                          ? "有变化"
                          : "无变化"
                          : ""
                          }}
                        </td>
                        <td :colspan="1">{{ item.companyNum }}</td>
                        <td :colspan="1">
                          <template v-if="item.taskType === '工商代办'">-</template>
                          <template v-else-if="editStatus">
                            <el-input-number v-model="item.price" size="small" placeholder="" :precision="2"
                              :controls="false" style="width: 100%"
                              @change="(arg) => itemChangeHandle(item, 'price')" />
                          </template>
                          <template v-else>{{ rowNum(item.price) }}</template>
                        </td>
                        <td :colspan="1">{{ rowNum(item.amount) }}</td>
                        <td :colspan="1">
                          <template v-if="item.taskType === '工商代办'">-</template>
                          <template v-else-if="editStatus">
                            <el-input-number v-model="item.discountPrice" size="small" placeholder="" :precision="2"
                              :controls="false" style="width: 100%" @change="
                                (arg) => itemChangeHandle(item, 'discountPrice')
                              " />
                          </template>
                          <template v-else>{{
                            rowNum(item.discountPrice)
                            }}</template>
                        </td>
                        <td :colspan="1">{{ rowNum(item.discountAmount) }}</td>
                        <td :colspan="1">
                          <template v-if="editStatus">
                            <el-input-number v-model="item.freeAmount" size="small" placeholder="" :precision="2"
                              :controls="false" style="width: 100%" :max="
                                item.discountPrice == null
                                  ? item.amount
                                  : item.discountAmount
                              " @change="
                                (arg) =>
                                  itemChangeHandle(item, 'freeAmount', arg)
                              " />
                          </template>
                          <template v-else>{{
                            rowNum(item.discountPrice)
                            }}</template>
                        </td>
                        <td :colspan="1">{{ rowNum(item.actuallyAmount) }}</td>
                        <td :colspan="2" class="tdLast" v-if="index === 0" :rowspan="form.collect.length"
                          style="width: 300px">
                          <template v-if="editStatus">
                            <el-input v-model="form.description" type="textarea" style="width: 100%" autosize
                              maxlength="200" show-word-limit />
                          </template>
                          <template v-else>{{ form.description }}</template>

                          <!-- <template>{{ form.descrpition }}</template> -->
                        </td>
                      </tr>
                      </tbody>
                    </table>
                    <table class="header" cellspacing="0" cellpadding="0">
                      <tbody></tbody>
                    </table>
                  </el-tab-pane>
                  <el-tab-pane label="循环任务" name="loop">
                    <el-table v-loading="loading" :data="form.loopList" size="small" border height="100%">
                      <!-- <el-table-column label="工单号" align="center" prop="workOrderNo" width="200" /> -->
                      <el-table-column label="工作月" align="center" prop="workMonth">
                        <template #default="scope">
                          {{ scope.row.workMonth.substring(0, 7)}}
                        </template>
                      </el-table-column>
                      <el-table-column label="客户名称" align="center" width="150" prop="companyName" />
                      <el-table-column label="税号" align="center" prop="socialCreditCode" width="150" />
                      <el-table-column label="注册地址" align="center" prop="formNo" width="120">
                        <template #default="scope">
                          {{ scope.row.province }}-{{ scope.row.city }}-{{
                          scope.row.district
                          }}
                        </template>
                      </el-table-column>
                      <el-table-column label="年收入" align="center" prop="annualIncome" width="100">
                      </el-table-column>
                      <el-table-column label="税务申报" align="center" width="80">
                        <template #default="scope">
                          {{ scope.row.isTax === 1 ? "是" : "否" }}
                        </template>
                      </el-table-column>
                      <el-table-column label="社保" prop="remainAmount" align="center" width="80">
                        <template #default="scope">
                          {{ scope.row.isSocialSecurity === 1 ? "是" : "否" }}
                        </template>
                      </el-table-column>
                      <el-table-column label="公积金" prop="status" align="center" width="80">
                        <template #default="scope">
                          {{ scope.row.isHousingFund === 1 ? "是" : "否" }}
                        </template>
                      </el-table-column>
                      <el-table-column label="纳税性质" align="center" prop="taxType" width="100" />
                      <el-table-column label="征收方式" align="center" prop="collectionMethod" width="100" />
                      <!-- <el-table-column
                      label="定额金额"
                      align="center"
                      prop="quotaAmount"
                      width="80"
                    /> -->
                      <el-table-column label="是否零申报" align="center" prop="isZero" width="80">
                        <template #default="scope">
                          {{ scope.row.isZero === 1 ? "是" : "否" }}
                        </template>
                      </el-table-column>
                      <el-table-column label="实际年收入" align="center" prop="actuallyAnnualIncome" width="100" />
                      <el-table-column label="社保有无变化" prop="status" align="center" width="100">
                        <template #default="scope">
                          {{
                          scope.row.changedSocialSecurity === 1 ? "是" : "否"
                          }}
                        </template>
                      </el-table-column>
                      <el-table-column label="公积金有无变化" prop="status" align="center" width="100">
                        <template #default="scope">
                          {{ scope.row.changedHousingFund === 1 ? "是" : "否" }}
                        </template>
                      </el-table-column>
                      <el-table-column label="累计年收入" prop="status" align="center" width="100">
                        <template #default="scope">
                          {{ scope.row.cumulativeIncome }}
                        </template>
                      </el-table-column>
                    </el-table>
                  </el-tab-pane>
                  <el-tab-pane label="工商任务" name="once">
                    <el-table v-loading="loading" :data="form.onceList" size="small" border height="100%">
                      <!-- <el-table-column label="工单号" align="center" prop="workOrderNo" width="200" /> -->
                      <el-table-column label="客户名称" align="center" width="200" prop="companyName" />
                      <el-table-column label="税号" align="center" prop="socialCreditCode" width="150" />
                      <el-table-column label="所在区" align="center" prop="formNo" width="150">
                        <template #default="scope">
                          {{ scope.row.province }}-{{ scope.row.city }}-{{
                          scope.row.district
                          }}
                        </template>
                      </el-table-column>
                      <el-table-column label="办理事项" align="center" prop="annualIncome" width="120">
                        <template #default="scope">
                          {{ scope.row.taskTypeName }}-{{
                          scope.row.taskTypeDetailName
                          }}
                        </template>
                      </el-table-column>
                      <el-table-column label="下单时间" prop="entrustDate" align="center" width="100">
                      </el-table-column>
                      <el-table-column label="完成时间" prop="finishedDate" align="center" width="100">
                      </el-table-column>
                      <el-table-column label="收费" prop="amount" align="center" width="100">
                        <template #default="scope">
                          <template v-if="editStatus">
                            <el-input-number v-model="scope.row.amount" size="small" placeholder="" :precision="2"
                              :controls="false" style="width: 100%" @change="onceChangeHandle(scope.row, 'amount')" />
                          </template>
                          <template v-else>{{ scope.row.amount }}</template>
                        </template>
                      </el-table-column>
                      <el-table-column label="说明" align="center" prop="description" />
                    </el-table>
                  </el-tab-pane>
                </el-tabs>
              </el-col>
            </el-row>
          </el-form>
        </div>
      </el-drawer>
      <!-- 图片预览 -->
      <el-image-viewer v-if="showViewer" :url-list="currentFileList" @close="closeImages" :initial-index="showIndex" />
  </div>
</template>
<script setup>
  import { getToken } from "@/utils/auth";
  import { rowNum } from "@/utils/index";
  import {
    addFollow,
    listFollow,
    delFollow,
  } from "@/api/business/crm/companyFollowDetail";
  import {
    getDeduct,
    genDeduct,
    addDeduct,
    updateDeduct,
    exportAccountStatement
  } from "@/api/business/entrust/deduct";
  import useUserStore from "@/store/modules/user";
  import { deepClone } from "@/utils";
  import {
    incomeDefault,
    taxTypes,
    confirmDefault,
    collectionMethods,
    yesOrNo,
  } from "@/utils/default";
  const { proxy } = getCurrentInstance();
  /** 父组件传参 */
  const props = defineProps({
    getList: {
      type: Function,
      default: () => { },
    },
  });

  const { getList } = toRefs(props);
  /** 字典数组区 */
  import { uploadFile } from "@/api/tool/file";
  const CustomerFormComRef = ref(null);
  /** 表单抽屉 页变量 */
  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 currentMember = {};
  const activeName = ref("base");
  const provinces = ref(proxy.region.getProvinces());
  provinces.value.unshift({ code: "", name: "全部" });
  const cities = ref([]);
  const districts = ref([]);
  const sourceCategories = ref([]);
  const area = ref([]);
  const fileList = ref([]);
  const condition = ref({});
  const showViewer = ref(false);
  const currentFileList = ref([]);
  const showIndex = ref(0);
  const types = ref([]);
  const taxDeclarationCategories = ref([]);

  const baseUrl = ref(import.meta.env.VITE_APP_BASE_API);

  const webHost = import.meta.env.VITE_APP_BASE_API;
  const setHeaders = {
    Authorization: getToken(),
  };
  const data = reactive({
    form: {},
  });

  const { form, rules } = toRefs(data);

  const contactorEmptyData = {
    id: null,
    name: "",
    position: "",
    gender: "男",
    phone: "",
    email: "",
    isMain: "是",
    remark: "",
  };
  const deductEmptyData = {
    id: null,
    collect: [],
    loopList: [],
    onceList: [],
    creatorId: useUserStore().user.id,
  };
  const queryRadio = ref("base-form");
  const defaultIsZero = ref(0);
  /***********************  表单页方法 ****************************/

  function sourceValidator(rule, value, callback) {
    // console.log(form.value)
    if (form.value.sourceCategoryName === "") {
      callback(new Error("来源类型不能为空"));
      return;
    }
    // console.log(`referrerDataSource: ${form.value.referrerDataSource}`)
    // console.log(`sourceName: ${form.value.sourceName}`)
    if (
      form.value.referrerDataSource !== "" &&
      form.value.referrerDataSource != null &&
      (form.value.sourceName === "" || form.value.sourceName == null)
    ) {
      callback(new Error("来源不能为空"));
      return;
    }
    return callback();
  }

  /** 抽屉打开 */
  function open(id) {
    reset();
    visible.value = true;
    if (id) {
      loading.value = true;
      getDeduct(id).then((response) => {
        form.value = response.data;
        editStatus.value = false;
        title.value = "修改客户";
        condition.value.entrustOrderId = form.value.entrustOrderId;
        condition.value.startMonth = form.value.startMonth;
        condition.value.endMonth = form.value.endMonth;
      }).finally
      (() => {
        loading.value = false;
      });
    }
  }

  function add(options) {
    reset();
    visible.value = true;
    loading.value = true;
    condition.value = options
    genDeduct(options).then((res) => {
      form.value = res.data;
      editStatus.value = true;
    }).finally
      (() => {
        loading.value = false;
      });
  }
  /**  取消按钮 */
  function cancel() {
    visible.value = false;
    reset();
  }

  /** 表单重置 */
  function reset() {
    form.value = deepClone(deductEmptyData);
    if (CustomerFormComRef.value) CustomerFormComRef.value.reset();
    proxy.resetForm("companyRef");
  }

  /** 上传后方法处理 */
  function uploadSuccess(res) {
    if (res.code == 200) {
      const newAttach = {
        name: res.data.name,
        url: res.data.url,
      };
      form.value.attaches.push(newAttach);
    } else {
      proxy.$modal.msgError("上传失败" + res.msg);
    }
  }

  function handleDownLoad(url) {
    window.open(webHost + url);
  }

  // 全屏缩放
  function handleScreen() {
    const dom = document.querySelector(
      ".list-container > .el-drawer__wrapper > .el-overlay"
    );
    isFullscreen.value = !isFullscreen.value;
    dom.style.position = isFullscreen.value ? "fixed" : "absolute";
  }

  function getForm() {
    loading.value = true;
    getCompany(form.value.id).then((response) => {
      loading.value = false;
      form.value = response.data;
      CustomerFormCom.value.setForm(form.value);
    });
  }

  function checkZero() {
    if (defaultIsZero.value === 1) {
      return true;
    } else if (
      defaultIsZero.value != form.value.isZero &&
      form.value.isZero === 1
    ) {
      proxy.$modal.msgError("不可将非零申报客户改为零申报");
      return false;
    } else {
      return true;
    }
  }
  function exportExcel() {
    condition.value.title =  "(" + form.value.contactCompany + "-" + form.value.formNo+")";
    exportAccountStatement(condition.value)
  }
  /** 提交保存 */
  function submitForm() {
    if (form.value.amount < 0) {
      proxy.$modal.msgError("本期消耗不能小于0");
      return;
    }
    proxy.$modal.confirm("确认保存么").then((res) => {
      form.value.status = 0;
      if (form.value.id == null) {
        addDeduct(form.value).then((res) => {
          cancel();
          getList.value();
        });
      } else {
        updateDeduct(form.value).then((res) => {
          cancel();
          getList.value();
        });
      }
    });
  }

  /** 添加从表 */
  function handleAdd() {
    for (var i = 0; i < addDetailNum.value; i++) {
      form.value.members.push({});
    }
  }

  /** 删除从表 */
  function handleDel(index) {
    proxy.$modal
      .confirm("确定删除?")
      .then(() => {
        form.value.members.splice(index, 1);
      })
      .catch(() => {
        proxy.$modal.msg("已取消删除");
      });
  }

  function handleDelAttach(index) {
    proxy.$modal
      .confirm("确定删除?")
      .then(() => {
        form.value.attaches.splice(index, 1);
      })
      .catch(() => {
        proxy.$modal.msg("已取消删除");
      });
  }

  /** 单选添加 */
  function handleDialogOpen(person) {
    multiple.value = false;
    currentMember.value = person;
    proxy.$refs.personRef.open();
  }

  /** 多选添加 */
  function handleAddBatch() {
    multiple.value = true;
    proxy.$refs.personRef.open();
  }

  function handleSingleSelected(person) {
    // console.log('单选带回', person)
    if (
      form.value.members.findIndex((item) => item.personId === person.id) === -1
    ) {
      currentMember.value.personId = person.id;
      currentMember.value.name = person.name;
      currentMember.value.code = person.code;
      currentMember.value.gender = person.gender;
      currentMember.value.age = person.age;
      currentMember.value.phone = person.phone;
    } else {
      proxy.$modal.msgError(person.name + "已存在,请勿重复添加！");
    }
  }

  function handleMultipleSelected(selection) {
    // console.log('多选回带', selection)
    for (var i = 0; i < selection.length; ++i) {
      const newPerson = {};
      if (
        form.value.members.findIndex(
          (item) => item.personId === selection[i].id
        ) === -1
      ) {
        newPerson.personId = selection[i].id;
        newPerson.name = selection[i].name;
        newPerson.code = selection[i].code;
        newPerson.gender = selection[i].gender;
        newPerson.age = selection[i].age;
        newPerson.phone = selection[i].phone;
        form.value.members.push(newPerson);
      } else {
        proxy.$modal.msgError(selection[i].name + "已存在,请勿重复添加！");
      }
    }
  }

  function scrollTargetTo(target) {
    const targetElement = document.getElementById(target);
    if (targetElement) {
      targetElement.scrollIntoView();
    }
  }

  function validDetails() {
    const contactors = form.value.contactors;
    if (contactors.length === 0) {
      return true;
    }
    form.value.contactors.forEach(function (val, index) {
      if (val.name === "") {
        proxy.$modal.msgError(`第 ${index + 1} 行联系人的姓名不能为空`);
        _isNull = true;
        return false;
      } else if (val.position === "") {
        proxy.$modal.msgError(`第 ${index + 1} 行联系人的角色不能为空`);
        _isNull = true;
        return false;
      }
    });
    return true;
  }

  function itemChangeHandle(item, field) {
    const price = item.price == null ? 0 : item.price;
    const num = item.companyNum == null ? 0 : item.companyNum;
    const discountPrice = item.discountPrice == null ? 0 : item.discountPrice;
    const amount = price * num;
    const freeAmount = item.freeAmount == null ? 0 : item.freeAmount;
    item.amount = amount;
    item.discountAmount = discountPrice * num;
    item.actuallyAmount =
      (item.discountPrice == null ? item.amount : item.discountAmount) -
      freeAmount;
    computedTotal();
  }

  function itemChangeHandleEnd(item, field, arg) {
    let freeAmount = item.freeAmount;
    let discountPrice = item.discountPrice;
    let discountAmount = item.discountAmount;
    let num = item.companyNum == null ? 0 : item.companyNum;
    let amount = item.amount;
    let actuallyAmount = item.actuallyAmount;
    if (item.taskType === "工商代办") {
      switch (field) {
        case "freeAmount":
          freeAmount = arg == null ? 0 : arg;
          const actuallyAmount =
            freeAmount > item.amount ? 0 : item.amount - freeAmount;
          item.freeAmount = freeAmount > item.amount ? item.amount : freeAmount;
          item.actuallyAmount = actuallyAmount;
          break;
      }
    } else {
      switch (field) {
        case "discountPrice":
          discountPrice = arg;
          discountAmount = discountPrice * item.companyNum;
          item.discountAmount = discountAmount;
          actuallyAmount =
            freeAmount > discountAmount ? 0 : discountAmount - freeAmount;
          item.actuallyAmount = actuallyAmount;
          item.freeAmount =
            freeAmount > discountAmount ? discountAmount : freeAmount;
          break;
        case "price":
          price = arg;
          amount = price * num;
          item.amount = amount;
          break;
        case "freeAmount":
          actuallyAmount =
            freeAmount > discountAmount ? 0 : discountAmount - freeAmount;
          item.actuallyAmount = actuallyAmount;
          item.freeAmount =
            freeAmount > discountAmount ? discountAmount : freeAmount;
          break;
      }
    }

    computedTotal();
  }

  function computedTotal() {
    let totalAmount = 0;
    form.value.collect.forEach((item) => {
      totalAmount += item.actuallyAmount;
    });
    form.value.amount = totalAmount;
    form.value.remainAmount = form.value.prevRemainAmount - form.value.amount;
  }

  function onceChangeHandle() {
    let totalAmount = 0;
    form.value.onceList.forEach((item) => {
      totalAmount += item.amount == null ? 0 : item.amount;
    });
    const collect = form.value.collect.find((v) => v.taskType === "工商代办");
    collect.amount = totalAmount;
    collect.actuallyAmount = totalAmount;
    computedTotal();
  }

  function closeImages() {
    reset();
    showViewer.value = false;
  }

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

<style>
  .header {
    text-align: center;
    line-height: 30px;
  }

  .baseTable table tbody tr td {
    border-left: 1px solid #dadada;
    border-top: 1px solid #dadada;
    border-bottom: 1px solid #dadada;
    padding: 0;
    border-spacing: 0;
  }

  .tdLast {
    border-right: 1px solid #dadada;
  }
</style>