<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
            v-if="editStatus"
            type="primary"
            size="small"
            icon="Finished"
            @click="submitForm"
            >保存</el-button
          >
          <el-button
            v-show="!editStatus && form.verifyDate == null"
            type="warning"
            size="small"
            icon="Edit"
            v-hasPermi="['business:collection: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-if="form.id && !editStatus && form.verifyStatus == 0"
              v-hasPermi="['business:archive:order:verify']" type="warning" size="small"
              @click="verifyHandler">审核通过</el-button>
            <el-button v-if="form.id && !editStatus && form.verifyStatus == 0"
              v-hasPermi="['business:archive:order:verify']" type="danger" size="small"
              @click="rejectHandler">驳回</el-button> -->
          <el-button
            v-show="form.id && !editStatus && form.verifyDate == null"
            v-hasPermi="['business:collection:verify']"
            type="primary"
            size="small"
            icon="Check"
            @click="verifyHandler"
            >收款审核</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>
        <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"
                  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"
                  :fetch-suggestions="querySearchAccountAsync"
                  :trigger-on-focus="true"
                  v-model="form.subsidiaryName"
                  placeholder="请输入收款账户"
                  style="width: 100%"
                  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"
                  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"
                  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"
                  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"
                  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"
                  v-model.trim="form.arriveDate"
                  size="small"
                  :clearable="true"
                  style="width: 100%"
                  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"
                  v-model.trim="form.arriveAmount"
                  size="small"
                  placeholder="收款金额"
                  :clearable="true"
                  :precision="2"
                  controls-position="right"
                  :controls="false"
                  @change="amountChange"
                />
                <span>{{ rowNum(form.arriveAmount) }}</span>
              </el-form-item>
            </el-col>
            <el-col v-if="form.status === 1" :span="6">
              <el-form-item label="审核意见：" required>
                <span>{{ form.verifyComment }}</span>
              </el-form-item>
            </el-col>
            <el-col v-if="form.status === 2" :span="6">
              <el-form-item label="驳回原因：" required>
                <span>{{ form.verifyComment }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="备注：">
                <el-input
                  v-if="editStatus"
                  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"
                    header-align="center"
                    align="right"
                  >
                    <template #default="scope">
                      <span>{{ rowNum(scope.row.amount) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="本次付款金额"
                    prop="arriveAmount"
                    width="100"
                    header-align="center"
                    align="right"
                  >
                    <template #default="scope">
                      <template v-if="editStatus">
                        <el-input-number
                          v-model="scope.row.arriveAmount"
                          size="small"
                          placeholder="本次付款金额"
                          :precision="2"
                          :controls="false"
                          style="width: 100%"
                          @change="
                            (arg) =>
                              amountChangeHandler(
                                arg,
                                scope.row,
                                'arriveAmount'
                              )
                          "
                        />
                      </template>
                      <template v-else>{{ rowNum(scope.row.amount) }}</template>
                    </template>
                  </el-table-column>
                  <el-table-column
                    label="已付款金额"
                    prop="arrived"
                    width="100"
                    align="right"
                    header-align="center"
                  >
                    <template #default="scope">
                      <span>{{ rowNum(scope.row.amount) }}</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" /> 附件
                  <span style="color: red"><i style="color: red" /> *</span>
                </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"
                    min-width="200"
                    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="操作" min-width="60" 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" size="small">
        <el-form-item label="审核状态">
          <el-select
            v-model.trim="form.status"
            placeholder="请选择"
            size="small"
          >
            <el-option
              v-for="i in verified"
              :key="i.value"
              :label="i.label"
              :value="i.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="实际付款时间" required>
          <el-date-picker
            v-model.trim="form.actuallyDate"
            size="small"
            :clearable="true"
            format="YYYY-MM-DD HH:mm:ss"
            value-format="YYYY-MM-DD HH:mm:ss"
            align="center"
            type="datetime"
            placeholder="实际付款时间"
          />
        </el-form-item>
        <el-form-item
          :label="form.status == 2 ? '驳回原因' : '审核意见'"
          :prop="verifyComment"
        >
          <el-input
            type="textarea"
            maxlength="200"
            show-word-limit
            v-model.trim="form.verifyComment"
            :rows="3"
            placeholder="请输入审核意见"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button
            type="primary"
            icon="Finished"
            size="small"
            @click="verifyUpload()"
            >确 定</el-button
          >
          <el-button icon="Close" size="small" @click="rejectCancel"
            >取 消</el-button
          >
        </div>
      </template>
    </el-dialog>
  </div>
</template>
<script setup>
import { uploadFile } from "@/api/tool/file";
// import {
//   getOrder,
//   initTaskTypes,
//   addOrder,
//   updateOrder,
//   verifyOrder,
//   alterOrder,
//   dissolutionOrder,
// } from "@/api/business/crm/contract";
import {
  listContract,
  listAccount,
  getCollection,
  getCollectionByContract,
  saveCollection,
  verifyCollection,
} 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 sourceCategories = ref([]);
const type = ref("");

const rejectOpen = ref(false);

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 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" },
  verified: [
    {
      value: 0,
      label: "未审核",
    },
    {
      value: 1,
      label: "通过",
    },
    {
      value: 2,
      label: "不通过",
    },
  ],
});
const { form, rules, timeOptions, verified } = toRefs(data);
/***********************  方法区  ****************************/
/** 打开抽屉 */
function open(id) {
  reset();
  visible.value = true;
  editStatus.value = true;
  // console.log(virtual_address.value)
  getCollection(id).then((res) => {
    form.value = res.data;
    editStatus.value = false;
    // editStatus.value = true
  });
}

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

// 数字格式化
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 reset() {
  form.value = JSON.parse(JSON.stringify(contractEmpty));
  console.log("重置表单", form.value);
  type.value = "";
  // console.log(form)
  // proxy.resetForm("orderRef");
}

/** 全屏缩放 */
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() {
  proxy.$refs["orderRef"].validate((valid) => {
    if (valid && detailValid()) {
      const formValue = form.value;
      saveCollection(formValue).then((res) => {
        open(form.value.id);
        getList.value();
      });
    }
  });
}

function detailValid() {
  // 20240109 暂时附件非必填。
  // 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("取消审核");
  //   });
  rejectOpen.value = true;
}

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

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

function rejectReset() {}

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

function verifyUpload() {
  // const formValue = proxy.deepClone(form.value);
  // formValue.verifyStatus = status;
  // formValue.status = status;
  if (form.value.status === 0) {
    proxy.$modal.msgError("请选择审核结果");
    return;
  }
  if (form.value.actuallyDate == null || form.value.actuallyDate === "") {
    proxy.$modal.msgError("请输入实际付款时间");
    return;
  }
  if (
    form.value.status === 2 &&
    (form.value.verifyComment == null || form.value.verifyComment === "")
  ) {
    proxy.$modal.msgError("请输入审核意见");
    return;
  }
  form.value.arriveStatus = form.value.status === 1 ? 1 : 0;
  verifyCollection(form.value).then((res) => {
    open(form.value.id);
    getList.value();
    rejectCancel();
    proxy.$modal.mseSuccess("保存成功");
  });
}

/** 文件上传 */
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;
    if (form.value.arriveAmount > 0)
      form.value.arriveStatus =
        form.value.arriveAmount === form.value.amount ? 1 : 2;
    else form.value.arriveStatus = 0;
  }
}
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;
}

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("取消删除");
    });
}

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