<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">
                <el-link :underline="false" type="primary" @click="handleInfo(form)" >{{ form.companyName }}</el-link>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="合同编号：" prop="remark">
                <el-link  :underline="false" type="primary" @click="handleContract(form)" >{{ form.contractNo }}</el-link>
              </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" disabled />
                <span v-else>{{ form.arriveAmount }}</span>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="签单类型" prop="isNew">
                <el-radio-group v-model="form.isNew" disabled>
                  <el-radio :label="0">新签</el-radio>
                  <el-radio :label="1">续签</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="是否为项目" prop="isProject">
                <el-radio-group v-model="form.isProject">
                  <el-radio :label="0">项目</el-radio>
                  <el-radio :label="1">非项目</el-radio>
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="项目编号" prop="projectNo">
                <el-input style="width: 100%" v-model.trim="form.projectNo" size="small" placeholder="项目编号"
                  :clearable="true" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="项目名称" prop="projectName">
                <el-input style="width: 100%" v-model.trim="form.projectName" size="small" placeholder="项目名称"
                  :clearable="true" />
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="项目主体名称" prop="projectMainName">
                <el-input style="width: 100%" v-model.trim="form.projectMainName" size="small" placeholder="项目主体名称"
                  :clearable="true" />
              </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="explain" align="center" show-overflow-tooltip>
                  </el-table-column>
                  <el-table-column label="服务金额" prop="amount" width="150" align="center">
                    <template #default="scope">
                      <span>{{ rowNum(scope.row.amount) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="本次付款金额" prop="arriveAmount" width="150" 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="150" align="center">
                    <template #default="scope">
                      <span>{{ rowNum(scope.row.arrived) }}</span>
                    </template>
                  </el-table-column>
                  <el-table-column label="备注" prop="remark" width="250" align="center">
                    <template #default="scope">
                      <template v-if="editStatus">
                        <el-input v-model="scope.row.remark" placeholder="备注" size="small" />
                      </template>
                      <template v-else>{{ scope.row.remark }}</template>
                    </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>
          <span style="font-size: 14px; margin-top: 10px;">申请人：{{ form.applierName }}</span> <br />
          <span style="font-size: 14px;">制单时间：{{ form.createTime }}</span> <br />
        </div>
      </div>
    </el-drawer>
    <el-dialog title="驳回详情" v-model="rejectOpen" width="500px" append-to-body draggable :close-on-click-modal = "false">
      <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>
    <company-form ref="companyRef" :get-list="getList"></company-form>
    <contract-form ref="contractRef" :get-list="getList" />
  </div>
</template>
<script setup>
  import { uploadFile } from "@/api/tool/file";

  import {
    listAccount,
    listContract,
    getCollection,
    getCollectionByContract,
    getCollectionDetail,
    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 companyForm from "@/views/business/crm/company/formView.vue";
  import contractForm from "@/views/business/crm/order/form.vue";
  import match from "@/utils/match";
  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: reactive({}),
    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";
  }

  /** 提交按钮 */
  async function submitForm() {
    // 应收款金额  和明细比较 如果大于应收内容 提示 当前的合同提过的收款申请总金额超过当前合同金额，不可提交，如有需要请跟财务人员联系
    const res = await getCollectionDetail(form.value.contractId);
    if (res.data == null || res.data.length == 0) {
      const amount = form.value.arriveAmount;
      if (amount > form.value.contractAmount) {
        proxy.$modal.msgError("当前的合同提过的收款申请总金额超过当前合同金额，不可提交，请联系财务人员。");
        return false;
      }
      for (let i = 0; i < form.value.details.length; i++) {
        let item = form.value.details[i];
         if (item.arriveAmount != null && item.amount < item.arriveAmount) {
        proxy.$modal.msgError("当前的" + item.taskTypeName + "收款申请总金额超过当前服务金额，不可提交，请联系财务人员。");
        return false;
      }
      }
    } else {
      const countAmount = res.data.map((item) => item.arriveAmount).reduce((total, number) => {
        return total + number;
      });
      const amount = countAmount + form.value.arriveAmount;
      if (amount > form.value.contractAmount) {
        proxy.$modal.msgError("当前的合同提过的收款申请总金额超过当前合同金额，不可提交，请联系财务人员。");
        return false;
      }
      for (let i = 0; i < form.value.details.length; i++) {
        let item = form.value.details[i];
        let countAmount = 0;
        for (let j = 0; j < res.data.length; j++) {
          let match = res.data[j];
          if (item.taskTypeId == match.taskTypeId) {
            countAmount += match.arriveAmount;
          }
        }
        if (item.amount < match.add(item.arriveAmount, countAmount)) {
          proxy.$modal.msgError("当前的" + item.taskTypeName + "收款申请总金额超过当前服务金额，不可提交，请联系财务人员。");
          return false;
        }
      }
    }

    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 handleInfo(row) {
    proxy.$refs.companyRef.open(row.companyId);
  }
  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 handleContract(){
    proxy.$refs.contractRef.open(form.value.contractId);
  }

  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;
      }
      nextTick(() => {
        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>