<template>
  <!-- 添加或修改项目信息对话框 -->
  <div class="el-drawer__wrapper">
    <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-group>
            <el-button
              v-if="editStatus"
              type="primary"
              size="small"
              icon="Finished"
              @click="submitForm"
              >保存</el-button
            >
            <el-button
              v-else-if="form.verifyStatus == 0"
              type="warning"
              size="small"
              icon="Edit"
              @click="editStatus = true"
              >修改</el-button
            >
            <el-button
              v-if="form.id && editStatus"
              type="info"
              size="small"
              icon="Close"
              @click="editStatus = false"
              >取消修改</el-button
            >
            <el-button
              v-if="form.id"
              type="success"
              size="small"
              @click="getForm"
            >
              <i class="fa fa-refresh" aria-hidden="true" /> 刷新
            </el-button>
            <el-button
              v-show="form.id && !editStatus && form.verifyStatus == 0"
              v-hasPermi="['business:archive:order:verify']"
              type="warning"
              size="small"
              @click="verifyHandler"
              >审核通过</el-button
            >
            <el-button
              v-show="form.id && !editStatus && form.verifyStatus == 0"
              v-hasPermi="['business:archive:order:verify']"
              type="danger"
              size="small"
              @click="rejectHandler"
              >驳回</el-button
            >
          </el-button-group>
          <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>
        <div
          class="Y-scrollbar"
          style="
            position: absolute;
            top: 32px;
            bottom: 0;
            width: 100%;
            overflow: auto;
          "
        ></div>
        <el-form
          ref="orderRef"
          class="master-container"
          size="small"
          :model="form"
          :rules="rules"
          label-width="100px"
        >
          <el-row :gutter="30">
            <el-col :span="6">
              <el-form-item label="收款流水号：">
                <el-input
                  v-if="editStatus"
                  style="width: 100%"
                  v-model.trim="form.flowNo"
                  readonly
                  size="small"
                  type="text"
                  placeholder="收款流水号"
                  :clearable="true"
                />
                <span v-else>{{ form.flowNo }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="收款账户：" prop="subsidiaryName">
                <el-autocomplete
                  v-if="editStatus"
                  style="width: 100%"
                  :fetch-suggestions="querySearchAccountAsync"
                  :trigger-on-focus="true"
                  v-model="form.subsidiaryName"
                  placeholder="请输入收款账户"
                  popper-class="my-autocomplete"
                  @select="handleSelectAccount"
                >
                  <template #default="{ item }">
                    <div
                      style="
                        display: flex;
                        flex-direction: row;
                        justify-content: space-between;
                      "
                    >
                      <div class="name" style="font-size: 12px">
                        {{ item.name }}
                      </div>
                      <span
                        class="code"
                        style="font-size: 10px; color: darkgrey"
                        >{{ item.code }}</span
                      >
                    </div>
                  </template>
                </el-autocomplete>
                <span v-else>{{ form.subsidiaryName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="收款开户行：" prop="subsidiaryBankName">
                <el-input
                  v-if="editStatus"
                  style="width: 100%"
                  v-model.trim="form.subsidiaryBankName"
                  size="small"
                  type="text"
                  placeholder="开户行"
                  :clearable="true"
                  :readonly="true"
                />
                <span v-else>{{ form.subsidiaryBankName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="收款账号：" prop="subsidiaryBankAccount">
                <el-input
                  v-if="editStatus"
                  style="width: 100%"
                  v-model.trim="form.subsidiaryBankAccount"
                  size="small"
                  type="text"
                  placeholder="账号"
                  :clearable="true"
                  :readonly="true"
                />
                <span v-else>{{ form.subsidiaryBankAccount }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="付款名称：" prop="applyName">
                <el-input
                  v-if="editStatus"
                  style="width: 100%"
                  v-model.trim="form.applyName"
                  size="small"
                  type="text"
                  placeholder="付款名称"
                  :clearable="true"
                />
                <span v-else>{{ form.applyName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="付款账号：" prop="appyAccount">
                <el-input
                  v-if="editStatus"
                  style="width: 100%"
                  v-model.trim="form.appyAccount"
                  size="small"
                  type="text"
                  placeholder="付款账号"
                  :clearable="true"
                />
                <span v-else>{{ form.appyAccount }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="到账日期：" prop="arriveDate">
                <el-date-picker
                  v-if="editStatus"
                  style="width: 100%"
                  v-model.trim="form.arriveDate"
                  size="small"
                  :clearable="true"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD HH:mm:ss"
                  align="center"
                  type="date"
                  placeholder="到账日期"
                />
                <span v-else>{{ form.arriveDate }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="到账时间：" prop="arriveTime">
                <el-time-select
                  v-if="editStatus"
                  style="width: 100%"
                  v-model.trim="form.arriveTime"
                  :picker-options="timeOptions"
                  placeholder="选择时间"
                />
                <span v-else>{{ form.arriveTime }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户名称：" prop="companyName">
                <span>{{ form.companyName }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="合同编号：" prop="remark">
                <span>{{ form.contractNo }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="应收款金额：" prop="remark">
                <span>{{ rowNum(form.contractAmount) }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="未收款金额：" prop="remark">
                <span>{{ rowNum(form.nonpaymentAmount) }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="收款金额：" required>
                <el-input-number
                  v-if="editStatus"
                  style="width: 100%"
                  v-model.trim="form.arriveAmount"
                  size="small"
                  placeholder="收款金额"
                  :clearable="true"
                  :precision="2"
                  controls-position="right"
                  :controls="false"
                  @change="amountChange"
                />
                <span v-else>{{ form.arriveAmount }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注：">
                <el-input
                  v-if="editStatus"
                  style="width: 100%"
                  v-model.trim="form.remark"
                  size="small"
                  type="text"
                  placeholder="备注"
                  :clearable="true"
                />
                <span v-else style="word-break: break-all">{{
                  form.remark
                }}</span>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <div class="details-container">
          <el-row :gutter="2" style="height: 100%">
            <el-col :span="18">
              <div class="details-head">
                <div class="title">
                  <i class="fa fa-th-list" aria-hidden="true" /> 收款明细
                </div>
              </div>
              <div class="details-body">
                <el-table
                  ref="filesTable"
                  :data="form.details"
                  size="small"
                  height="100%"
                  border
                  header-row-class-name="list-header-row"
                  highlight-current-row
                >
                  <el-table-column
                    type="index"
                    label="序号"
                    width="47"
                    align="center"
                  />
                  <el-table-column
                    label="任务名称"
                    prop="taskTypeName"
                    align="center"
                    show-overflow-tooltip
                  >
                  </el-table-column>
                  <el-table-column
                    label="任务金额"
                    prop="amount"
                    width="100"
                    align="center"
                  >
                    <template #default="scope">
                      <span>{{ rowNum(scope.row.amount) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="本次付款金额"
                    prop="arriveAmount"
                    width="100"
                    align="center"
                  >
                    <template #default="scope">
                      <template v-if="editStatus">
                        <el-input-number
                          v-model="scope.row.arriveAmount"
                          size="small"
                          :min="0.0"
                          placeholder="本次付款金额"
                          :precision="2"
                          :controls="false"
                          style="width: 100%"
                          @change="
                            (arg) =>
                              amountChangeHandler(
                                arg,
                                scope.row,
                                'arriveAmount'
                              )
                          "
                        />
                      </template>
                      <template v-else>{{ scope.row.arriveAmount }}</template>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="已付款金额"
                    prop="arrived"
                    width="100"
                    align="center"
                  >
                    <template #default="scope">
                      <span>{{ rowNum(scope.row.arrived) }}</span>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-col>
            <el-col :span="6">
              <div class="details-head">
                <div class="title">
                  <i class="fa fa-th-list" aria-hidden="true" /> 附件
                  <i style="color: red">*</i>
                </div>
                <el-upload
                  v-if="editStatus"
                  action="#"
                  :http-request="upload"
                  :with-credentials="true"
                  :show-file-list="false"
                  multiple
                >
                  <el-button size="small" type="primary" icon="Upload"
                    >点击上传</el-button
                  >
                </el-upload>
              </div>
              <div class="details-body">
                <el-table
                  ref="filesTable"
                  :data="form.files"
                  size="small"
                  height="100%"
                  border
                  header-row-class-name="list-header-row"
                  highlight-current-row
                >
                  <el-table-column
                    type="index"
                    label="序号"
                    width="47"
                    align="center"
                  />
                  <el-table-column
                    label="文件名"
                    prop="originalFileName"
                    align="center"
                    show-overflow-tooltip
                  >
                    <template #default="scope">
                      <el-button
                        size="small"
                        type="primary"
                        link
                        @click="openFile(scope.row)"
                        >{{ scope.row.originalFileName }}</el-button
                      >
                    </template>
                  </el-table-column>
                  <el-table-column label="操作" width="50" align="center">
                    <template #default="scope">
                      <div v-if="editStatus">
                        <el-button
                          size="small"
                          link
                          type="danger"
                          @click="handlerDelAttach(scope.row, scope.$index)"
                          >删除</el-button
                        >
                      </div>
                    </template>
                  </el-table-column>
                </el-table>
              </div>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-drawer>
    <el-dialog
      title="驳回详情"
      v-model="rejectOpen"
      width="500px"
      append-to-body
      draggable
    >
      <el-form ref="dictRef" :model="form" label-width="100">
        <el-form-item label="驳回原因" :prop="verifyRemark">
          <el-input
            v-model.trim="form.verifyRemark"
            type="textarea"
            :rows="3"
            placeholder="请输入驳回原因"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="verifyUpload(4)">确 定</el-button>
          <el-button @click="rejectCancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { uploadFile } from "@/api/tool/file";

import {
  listAccount,
  listContract,
  getCollection,
  getCollectionByContract,
  saveCollection,
  setCollectionStatus,
} from "@/api/business/financial/collection";
import { listSource } from "@/api/settings/source";
import { listCompany } from "@/api/business/crm/company";
import { listUser } from "@/api/system/user";
import CustomerFormCom from "@/components/CustomerFormCom";
import { formatDate } from "@/utils/index";
import { ref } from "vue";
import useUserStore from "@/store/modules/user";
const { proxy } = getCurrentInstance();
const baseUrl = import.meta.env.VITE_APP_BASE_API;

/** 父组件传参 */
const props = defineProps({
  getList: {
    type: Function,
    default: () => {},
  },
});
const { getList } = toRefs(props);
/** 字典数组区 */
const { virtual_address } = proxy.useDict("virtual_address");
/** 表单抽屉 页变量 */
const title = ref("");
const loading = ref(false);
const multiple = ref(true);
const visible = ref(false);
const editStatus = ref(false);
const loopTasks = ref([]);
const onceTasks = ref([]);
const sourceCategories = ref([]);
const loops = ref([]);
const onces = ref([]);
const type = ref("");

const rejectOpen = ref(false);

// 循环任务明细
const loopDetails = ref([]);
// 单次任务明细
const onceDetails = ref([]);
const detailEmpty = {
  id: null,
  taskTypeName: "",
  taskTypeId: null,
  serviceNum: undefined,
  freeNum: undefined,
  price: undefined,
  amount: undefined,
  addressStyle: undefined,
  address: undefined,
  fictionAddressId: undefined,
  tenantId: undefined,
  province: "",
  city: "",
  district: "",
  addressStyle: 1,
  provinceId: undefined,
  processes: [],
  defaultProcesses: [],
};
const provinces = ref(proxy.region.getProvinces());
provinces.value.unshift({ code: "", name: "全部" });
const cities = ref([]);
const districts = ref([]);
const archiveInput = ref({});

const contractEmpty = {
  serviceType: 1,
  contractType: 0,
  formDate: formatDate(new Date(), "yyyy-MM-dd"),
  signerId: useUserStore().user.userId,
  signerName: useUserStore().user.nickName,
  files: [],
};
const isFullscreen = ref(false);
const webHost = import.meta.env.VITE_APP_BASE_API;
const data = reactive({
  form: {},
  rules: {},
  timeOptions: { start: "08:30", step: "00:15", end: "18:30" },
});
const { form, rules, timeOptions } = toRefs(data);
/***********************  方法区  ****************************/
/** 打开抽屉 */
function open(row) {
  reset();
  archiveInput.value = row;
  visible.value = true;
  getCollectionByContract(row).then((res) => {
    form.value = res.data;
    editStatus.value = true;
  });
}

// 数字格式化
function rowNum(num) {
  if (!num) {
    return;
  }
  num = num.toLocaleString(); // 3,000
  if (num.indexOf(".") == -1) {
    num = num + ".00"; //3,000.00
  } else if (num.charAt(num.indexOf(".") == num.length - 2)) {
    num = num + "0";
  }
  return num;
}

/** 取消按钮 */
function cancel() {
  visible.value = false;
  reset();
}

/** 表单重置 */
function reset() {
  form.value = JSON.parse(JSON.stringify(contractEmpty));
  loops.value = [];
  onces.value = [];
  loopDetails.value = [];
  onceDetails.value = [];
  type.value = "";
}

/** 全屏缩放 */
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 submitForm() {
  if (form.value.arriveAmount > form.value.contractAmount) {
    proxy.$modal.msgError("实际收款金额不能大于合同收款金额");
    return;
  }
  proxy.$refs["orderRef"].validate((valid) => {
    if (valid && detailValid()) {
      const formValue = form.value;
      saveCollection(formValue).then((res) => {
        if (res.code === 200) {
          archiveInput.value.collectionStatus = 1;
          setCollectionStatus(archiveInput.value);
          proxy.$message.success("保存成功");
        }
        cancel();
        getList.value();
      });
    }
  });
}

function detailValid() {
  // if (form.value.files.length === 0) {
  //   proxy.$modal.msgError("收款附件为空");
  //   return false;
  // }
  return true;
}

/** 查询表单信息  */
function getForm() {
  loading.value = true;
  getOrder(form.value.id).then((response) => {
    loading.value = false;
    form.value = response.data;
  });
}
function handleServiceTypeClick(tab) {
  computedService();
}

function verifyHandler() {
  proxy.$modal
    .confirm("是否确认审核?")
    .then((_) => {
      verifyUpload(1);
    })
    .catch((_) => {
      proxy.$modal.msg("取消审核");
    });
}

function rejectHandler() {
  rejectOpen.value = true;
}

function rejectCancel() {
  rejectOpen.value = false;
}

function rejectSubmitHandler() {
  if (form.value.verifyRemark === "" || form.value.verifyRemark == null) {
    proxy.$modal.msgError("请填写驳回原因");
    return;
  }
}

function verifyUpload(status) {
  const formValue = proxy.deepClone(form.value);
  formValue.verifyStatus = status;
  formValue.status = status;
  verifyOrder(formValue).then((res) => {
    getForm();
    getList.value();
    rejectCancel();
    proxy.$modal.msg("保存成功");
  });
}

/** 文件上传 */
function upload(param) {
  const fileForm = new FormData();
  fileForm.append("file", param.file);
  uploadFile(fileForm).then((res) => {
    if (res.code === 200) {
      const file = {};
      file.fileName = res.newFileName;
      file.url = res.url;
      file.originalFileName = res.originalFilename;
      file.fileUrl = res.fileName;
      form.value.files.push(file);
    }
  });
}

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

function amountChangeHandler(arg, row, field) {
  computeTotalAmount();
}

function computeTotalAmount() {
  let amount = 0;
  for (let index = 0; index < form.value.details.length; index++) {
    const element = form.value.details[index];
    amount += element.arriveAmount == null ? 0 : element.arriveAmount;
  }
  form.value.arriveAmount = amount;
}

function amountChange() {
  let amount = 0;
  if (form.value.details.length > 0) {
    for (let i = 0; i < form.value.details.length; i++) {
      amount = amount + form.value.details[i].arriveAmount;
    }

    form.value.arriveAmount = amount;
  }
}

function openFile(row) {
  window.open(`${baseUrl}${row.fileUrl}`);
}

function handlerDelAttach(row, index) {
  proxy.$modal
    .confirm("确认删除该项么？")
    .then((_) => {
      form.value.files.splice(index, 1);
    })
    .catch((err) => {
      proxy.$modal.msgError("取消删除");
    });
}

function querySearchAccountAsync(queryString, cb) {
  const query =
    queryString.length > 0
      ? { keyword: queryString, pageSize: 20, pageNum: 1 }
      : { pageSize: 20, pageNum: 1 };
  listAccount(query).then((res) => {
    cb(res.rows);
  });
}

function handleSelectAccount(item) {
  form.value.subsidiaryName = item.name;
  form.value.subsidiaryBankName = item.accountOpen;
  form.value.subsidiaryBankAccount = item.accountNum;
}

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