<template>
  <div style="width: 100%; padding: 0px 15px">
    <el-form
      :model="formData.data"
      :rules="rules"
      ref="formDom"
      label-position="top"
    >
      <div class="_t">基础信息</div>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="归属公司" prop="corporationId">
            <el-select
              v-model="formData.data.corporationId"
              placeholder="请选择"
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="item in companyData"
                :label="item.name"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="归属部门" prop="departmentId">
            <el-cascader
              v-model="formData.data.departmentId"
              :options="deptTreeData"
              :props="{
                value: 'deptId',
              }"
              clearable
              filterable
              style="width: 100%"
              @change="handleChangeDept"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="请款类型" prop="type">
            <el-select
              v-model="formData.data.type"
              placeholder="请选择"
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="item in fundsType"
                :label="item.dictValue"
                :value="item.dictKey"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="币种" prop="currency">
            <el-select
              v-model="formData.data.currency"
              placeholder="请选择"
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="item in currencyType"
                :label="item.dictValue"
                :value="item.dictKey"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="6">
          <el-form-item label="用款时间" prop="paymentTime">
            <el-date-picker
              v-model="formData.data.paymentTime"
              type="datetime"
              placeholder="请选择"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item label="用款说明" prop="paymentRemarks">
        <el-input
          v-model="formData.data.paymentRemarks"
          placeholder="请输入"
          type="textarea"
        >
        </el-input>
      </el-form-item>
      <el-form-item label="上传附件">
        <el-upload
          v-model="formData.data.fileList"
          :show-file-list="false"
          class="upload-demo"
          action="https://winfaster.obs.cn-south-1.myhuaweicloud.com"
          :data="uploadData"
          :on-preview="handlePreview"
          :before-upload="handleBeforeUpload"
        >
          <el-button type="primary">选择</el-button>
        </el-upload>
      </el-form-item>
      <div style="margin-bottom: 15px">
        <el-tag
          style="margin-right: 10px"
          class="ml-2"
          type="info"
          v-for="(item, index) in formData.data.fileList"
          :key="index"
          closable
          @close="handleClose(index)"
          >{{ item.fileName }}</el-tag
        >
      </div>
      <div class="_t">请款明细</div>
      <el-form-item>
        <el-button type="primary" @click="handleAddRow" style="margin: 10px 0">
          添加行
        </el-button>
        <el-table :data="formData.data.accountRequestFundsDetailList">
          <el-table-column prop="count" label="费用类型" min-width="150">
            <template #default="{ row, $index }">
              <el-form-item
                :prop="'accountRequestFundsDetailList.' + $index + '.costType'"
                :rules="rules.costType"
                :inline-message="true"
              >
                <el-select
                  v-model="row.costType"
                  placeholder="请选择"
                  filterable
                  style="width: 100%"
                >
                  <el-option
                    v-for="item in fundsCostType"
                    :label="item.dictValue"
                    :value="item.dictKey"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="count" label="款项说明" min-width="150">
            <template #default="{ row, $index }">
              <el-form-item
                :prop="'accountRequestFundsDetailList.' + $index + '.remarks'"
                :rules="rules.remarks"
                :inline-message="true"
              >
                <el-input
                  v-model="row.remarks"
                  placeholder="请输入"
                  type="textarea"
                />
              </el-form-item>
            </template>
          </el-table-column>
          <el-table-column prop="amount" label="请款金额" min-width="150">
            <template #default="{ row, $index }">
              <el-form-item
                :prop="'accountRequestFundsDetailList.' + $index + '.amount'"
                :rules="rules.amount"
                :inline-message="true"
              >
                <el-input-number
                  v-model="row.amount"
                  :precision="4"
                  :controls="false"
                  :min="0"
                  @change="handleChangeAmount"
                />
              </el-form-item>
            </template>
          </el-table-column>

          <el-table-column prop="zip" label="操作" width="100">
            <template #default="{ $index }">
              <el-button type="primary" link @click="handleRemove($index)"
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
      </el-form-item>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="请款总额" prop="total">
            <el-input
              v-model="formData.data.total"
              placeholder="请输入"
              disabled
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="单据数量" prop="quantity">
            <el-input v-model="formData.data.quantity" placeholder="请输入" />
          </el-form-item>
        </el-col>
      </el-row>
      <div class="_t">收付款信息</div>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="付款方式" prop="paymentMethod">
            <el-select
              v-model="formData.data.paymentMethod"
              placeholder="请选择"
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="item in fundsPaymentMethod"
                :label="item.dictValue"
                :value="item.dictKey"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="付款账户" prop="accountManagementId">
            <el-select
              v-model="formData.data.accountManagementId"
              placeholder="请选择"
              filterable
              style="width: 100%"
            >
              <el-option
                v-for="item in accountData"
                :label="item.alias"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="户名" prop="name">
            <el-input v-model="formData.data.name" placeholder="请输入" />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="银行账号" prop="accountOpening">
            <el-input
              v-model="formData.data.accountOpening"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="10">
        <el-col :span="6">
          <el-form-item label="开户银行" prop="openingBank">
            <el-input
              v-model="formData.data.openingBank"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="联行号 / SWIFT Code" prop="interbankNumber">
            <el-input
              v-model="formData.data.interbankNumber"
              placeholder="请输入"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </div>
</template>

<script setup>
import { ElMessage, ElMessageBox } from "element-plus";
import useUserStore from "@/store/modules/user";

const { proxy } = getCurrentInstance();

let formData = reactive({
  data: {
    paymentTime: "",
    accountRequestFundsDetailList: [],
    fileList: [],
  },
});
let rules = ref({
  corporationId: [
    { required: true, message: "请选择归属公司", trigger: "change" },
  ],
  departmentId: [
    { required: true, message: "请选择归属部门", trigger: "change" },
  ],
  type: [{ required: true, message: "请选择请款类型", trigger: "change" }],
  paymentTime: [
    { required: true, message: "请选择用款时间", trigger: "change" },
  ],
  currency: [{ required: true, message: "请选择币种", trigger: "change" }],
  paymentMethod: [
    { required: true, message: "请选择付款方式", trigger: "change" },
  ],
  accountManagementId: [
    { required: true, message: "请选择付款账号", trigger: "change" },
  ],
  costType: [{ required: true, message: "请选择费用类型", trigger: "change" }],
  remarks: [{ required: true, message: "请输入款项说明", trigger: "blur" }],
  amount: [{ required: true, message: "请输入请款金额", trigger: "blur" }],
});

const handleAddRow = () => {
  formData.data.accountRequestFundsDetailList.push({
    costType: "",
    remarks: "",
    amount: 0,
  });
};

const handleRemove = (index) => {
  formData.data.accountRequestFundsDetailList.splice(index, 1);
  handleChangeAmount();
};

// 提交方法
const formDom = ref(null);
const handleSubmit = async () => {
  const vaild = await formDom.value.validate();
  if (vaild) {
    if (formData.data.accountRequestFundsDetailList.length > 0) {
      return true;
    }
    ElMessage({
      message: "请添加请款明细！",
      type: "info",
    });
    return false;
  }
  return false;
};
// 获取用户信息并赋默认值
const userInfo = useUserStore().user;
// const tenantId = "@福建宏星！#￥%……&*（）";
const tenantId = userInfo.tenantId;

onMounted(() => {
  formData.data.paymentTime = proxy.parseTime(new Date());
  getDictData();
});
const companyData = ref([]);
const accountData = ref([]);
const deptTreeData = ref([]);
const fundsType = ref([]);
const fundsCostType = ref([]);
const fundsPaymentMethod = ref([]);
const currencyType = ref([]);

const getDictData = () => {
  // 获取归属公司数据
  proxy
    .post("/corporation/page", { pageNum: 1, pageSize: 9999 })
    .then((res) => {
      companyData.value = res.rows;
    });
  // 账户数据
  proxy
    .post("/accountManagement/page", { pageNum: 1, pageSize: 9999 })
    .then((res) => {
      accountData.value = res.rows;
    });

  // 部门树
  proxy
    .get("/tenantDept/list", {
      pageNum: 1,
      pageSize: 9999,
      tenantId: userInfo.tenantId,
    })
    .then((message) => {
      recursive(message.data);
      deptTreeData.value = proxy.handleTree(message.data, "deptId");
    });
  // 请款类型数据
  proxy
    .post("/dictTenantData/page", {
      pageNum: 1,
      pageSize: 999,
      tenantId: tenantId,
      dictCode: "founds_type",
    })
    .then((res) => {
      fundsType.value = res.rows;
    });
  // 请款费用类型数据
  proxy
    .post("/dictTenantData/page", {
      pageNum: 1,
      pageSize: 999,
      tenantId: tenantId,
      dictCode: "funds_cost_type",
    })
    .then((res) => {
      fundsCostType.value = res.rows;
    });
  // 请款付款方式数据
  proxy
    .post("/dictTenantData/page", {
      pageNum: 1,
      pageSize: 999,
      tenantId: tenantId,
      dictCode: "funds_payment_method",
    })
    .then((res) => {
      fundsPaymentMethod.value = res.rows;
    });

  // 币种数据
  proxy
    .post("/dictTenantData/page", {
      pageNum: 1,
      pageSize: 999,
      tenantId: tenantId,
      dictCode: "account_currency",
    })
    .then((res) => {
      currencyType.value = res.rows;
    });
};
const recursive = (data) => {
  data.map((item) => {
    item.label = item.deptName;
    item.id = item.corporationId;
    if (item.children) {
      recursive(item.children);
    } else {
      item.children = [];
    }
  });
};

// 接收父组件的传值
const props = defineProps({
  queryData: String,
});

// 部门变更逻辑
const handleChangeDept = (val) => {
  formData.data.departmentId = val[val.length - 1];
};
// 计算请款总金额
const handleChangeAmount = () => {
  let sum = 0;
  for (let i = 0; i < formData.data.accountRequestFundsDetailList.length; i++) {
    const e = formData.data.accountRequestFundsDetailList[i];
    sum += e.amount;
  }
  formData.data.total = sum;
};
// 上传附件
const uploadData = ref({});
const handleBeforeUpload = async (file) => {
  const res = await proxy.post("/fileInfo/getSing", { fileName: file.name });
  uploadData.value = res.uploadBody;
  formData.data.fileList.push({
    id: res.id,
    fileName: res.fileName,
    path: res.fileUrl,
    url: res.fileUrl,
    uid: file.uid,
  });
};
const handleClose = (index) => {
  formData.data.fileList.splice(index, 1);
};
// 向父组件暴露
defineExpose({
  submitData: formData.data,
  handleSubmit,
});
</script>


<style lang="scss" scoped>
._t {
  margin-bottom: 5px;
  font-size: 14px;
}
</style>