<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-show="form.status === 0" type="primary" size="small" icon="Finished"
            v-hasPermi="['business:deduct:confirm']" @click="handleConfirm">确认扣款</el-button>
          <el-button v-show="form.status === 0" type="danger" icon="back" size="small" @click="handleReject"
            v-hasPermi="['business:deduct:confirm']">驳回扣款</el-button>
          <el-button v-if="form.id" type="success" size="small" icon="refresh" @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"> 上期余额：{{ form.prevRemainAmount }} </el-col>
            <el-col :span="4"> 本期消耗：{{ form.amount }} </el-col>
            <el-col :span="4"> 本期余额：{{ 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">
                    <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: 100px">
                          说明
                        </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 }}月
                        </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">{{ item.price }}</td>
                        <td :colspan="1">
                          {{ item.amount }}
                        </td>
                        <td :colspan="1">{{ item.discountPrice }}</td>
                        <td :colspan="1">{{ item.discountAmount }}</td>
                        <td :colspan="1">{{ item.freeAmount }}</td>
                        <td :colspan="1">{{ item.actuallyAmount }}</td>
                        <td :colspan="2" class="tdLast" v-if="index === 0" :rowspan="form.collect.length">
                          {{ form.description }}
                        </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" 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="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="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="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="80">
                    </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 {
  addFollow,
  listFollow,
  delFollow,
} from "@/api/business/crm/companyFollowDetail";
import {
  getDeduct,
  genDeduct,
  addDeduct,
  updateDeduct,
  confirmDeduct,
  rejectDeduct,
} 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 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) {
    getDeduct(id).then((response) => {
      form.value = response.data;
      editStatus.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;
  getDeduct(form.value.id).then((response) => {
    form.value = response.data;
    editStatus.value = false;
  });
}

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 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;
  }
  return true;
}
function closeImages() {
  reset();
  showViewer.value = false;
}

function handleConfirm() {
  proxy.$modal
    .confirm("确认扣款么？")
    .then((_) => {
      confirmDeduct(form.value).then((res) => {
        cancel();
        getList.value();
      });
    })
    .catch((_) => {
      proxy.$modal.msg("取消确认");
    });
}

function handleReject() {
  proxy.$modal
    .confirm("确认驳回么？")
    .then((_) => {
      rejectDeduct(form.value).then((res) => {
        cancel();
        getList.value();
      });
    })
    .catch((_) => {
      proxy.$modal.msg("取消确认");
    });
}

// 暴露给父组件的方法
defineExpose({
  open,
});
</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>