<template>
  <div class="pageIndexClass">
    <!-- <Banner /> -->
    <div class="content">
      <byTable :source="sourceList.data" :pagination="sourceList.pagination" :config="config" :loading="loading" highlight-current-row
               :selectConfig="selectConfig" :table-events="{
          select: select,
        }" :action-list="[]" @get-list="getList">
        <template #amount="{ item }">
          <div :style="'color: ' + (item.status === '10' ? '#04cb04;' : 'red;')">
            <span style="padding-right: 4px">{{ item.currency }}</span>
            <span v-if="item.status === '20'">-</span>
            <span>{{ moneyFormat(item.amount, 2) }}</span>
          </div>
        </template>
      </byTable>
    </div>
    <el-dialog title="拆分" v-if="dialogVisible" v-model="dialogVisible" width="800" v-loading="loading">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="submit">
        <template #money>
          <div style="width: 100%">
            <el-row :gutter="10">
              <el-col :span="6">
                <el-form-item>
                  <el-select v-model="formData.data.status" style="width: 100%" disabled>
                    <el-option v-for="item in status" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item>
                  <el-input v-model="formData.data.amount" placeholder="请输入金额" class="input-with-select" disabled>
                    <template #prepend>
                      <el-select v-model="formData.data.currency" placeholder="请选择币种" style="width: 100px" disabled>
                        <el-option v-for="item in accountCurrency" :key="item.value" :label="item.value" :value="item.value" />
                      </el-select>
                    </template>
                  </el-input>
                </el-form-item>
              </el-col>
            </el-row>
          </div>
        </template>
        <template #slot>
          <div style="width: 100%">
            <el-button type="primary" @click="addRow"> 添加 </el-button>
            <br />
            <el-table :data="formData.data.accountDeptRunningWaterDetailList">
              <el-table-column prop="deptId" label="部门">
                <template #default="{ row, $index }">
                  <el-form-item :prop="'accountDeptRunningWaterDetailList.' + $index + '.deptId'" :rules="rules.deptId" :inline-message="true">
                    <el-cascader v-model="row.deptId" :options="deptTreeData" :props="{
                        value: 'deptId',
                      }" clearable filterable style="width: 100%" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="amount" label="分拆金额">
                <template #default="{ row, $index }">
                  <el-form-item :prop="'accountDeptRunningWaterDetailList.' + $index + '.amount'" :rules="rules.amount" :inline-message="true">
                    <el-input-number onmousewheel="return false;" v-model="row.amount" placeholder="请输入金额" style="width: 100%" :precision="2"
                                     :controls="false" :min="0" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="remarks" label="备注">
                <template #default="{ row, $index }">
                  <el-form-item :prop="'accountDeptRunningWaterDetailList.' + $index + '.remarks'" :rules="rules.remarks" :inline-message="true">
                    <el-input v-model="row.remarks" placeholder="请输入" />
                  </el-form-item>
                </template>
              </el-table-column>
              <el-table-column prop="zip" align="center" label="操作" width="80">
                <template #default="{ $index }">
                  <el-button type="primary" link @click="handleRemove($index)">删除</el-button>
                </template>
              </el-table-column>
            </el-table>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="default">取 消</el-button>
        <el-button type="primary" @click="submitForm()" size="default" :loading="submitLoading"> 确 定 </el-button>
      </template>
    </el-dialog>

    <el-dialog title="调整部门" v-if="depModal" v-model="depModal" width="600" v-loading="loading">
      <p>部门名称</p>
      <el-cascader v-model="departmentId" :options="deptTreeData" :props="{
          value: 'deptId',
        }" clearable filterable style="width: 100%" />
      <template #footer>
        <el-button @click="depModal = false" size="default">取 消</el-button>
        <el-button type="primary" @click="submitDeptForm(departmentId)" size="default" :loading="submitLoading"> 确 定 </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ElMessage } from "element-plus";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import { computed, ref } from "vue";

const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
  },
});
let dialogVisible = ref(false);
let modalType = ref("add");
let rules = ref({
  type: [{ required: true, message: "请选择类型", trigger: "change" }],
  contactNumber: [
    { required: true, message: "请输入联系号码", trigger: "blur" },
  ],
  amount: [{ required: true, message: "请输入金额", trigger: "blur" }],
});
const status = ref([
  {
    label: "收入",
    value: "10",
  },
  {
    label: "支出",
    value: "20",
  },
]);
const accountCurrency = ref([]);
import Cookies from "js-cookie";
const { proxy } = getCurrentInstance();
const selectConfig = [];
const config = computed(() => {
  return [
    {
      attrs: {
        label: "资金账户",
        prop: "accountManagementName",
      },
    },
    {
      attrs: {
        label: "交易时间",
        prop: "transactionTime",
      },
    },
    {
      attrs: {
        label: "交易金额",
        slot: "amount",
      },
    },
    {
      attrs: {
        prop: "accountOpening",
        label: "对方账户",
      },
    },
    {
      attrs: {
        prop: "openingBank",
        label: "对方银行",
      },
    },
    {
      attrs: {
        prop: "name",
        label: "对方账号",
      },
    },
    {
      attrs: {
        prop: "remarks",
        label: "摘要",
      },
    },
    {
      attrs: {
        label: "操作",
        width: "200",
        align: "right",
      },
      renderHTML(row) {
        return [
          {
            attrs: {
              label: "调整部门",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              depModal.value = true;
              runningWaterId = row.id;
              dtlData.value = row;
              departmentId.value = [];
            },
          },
          {
            attrs: {
              label: "分拆",
              type: "primary",
              text: true,
            },
            el: "button",
            click() {
              getDtl(row);
            },
          },
        ];
      },
    },
  ];
});
const dtlData = ref({});
let formData = reactive({
  data: {
    type: "1",
  },
  treeData: [],
});
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const submit = ref(null);
const depModal = ref(false);
let deptTreeData = ref([]);
let departmentId = ref([]);
const getDept = async () => {
  // 部门树
  proxy
    .get("/tenantDept/list", {
      pageNum: 1,
      pageSize: 9999,
      tenantId: Cookies.get("tenantId"),
    })
    .then((message) => {
      recursive(message.data);
      deptTreeData.value = proxy.handleTree(message.data, "corporationId");
    });
};
getDept();
const submitDeptForm = async (departmentId) => {
  if (departmentId.length == 0) {
    ElMessage.error("请选择部门");
    return;
  }
  const params = {
    deptId: departmentId[departmentId.length - 1],
    accountDeptRunningWaterId: dtlData.value.accountDeptRunningWaterId,
    id: dtlData.value.id,
    amount: dtlData.value.amount,
  };
  proxy
    .post("/accountDeptRunningWaterDetail/add", params)
    .then(() => {
      ElMessage.success("调整部门成功");
      depModal.value = false;
      getList();
    })
    .catch((error) => {
      ElMessage.error(error);
    });
};
const recursive = (data) => {
  data.map((item) => {
    item.label = item.deptName;
    item.id = item.corporationId;
    if (item.children) {
      recursive(item.children);
    } else {
      item.children = [];
    }
  });
};
const formConfig = computed(() => {
  return [
    {
      type: "select",
      prop: "accountManagementId",
      label: "付款账户",
      required: true,
      disabled: true,
      isLoad: {
        url: "/accountManagement/page",
        req: {
          pageNum: 1,
          pageSize: 9999,
        },
        labelKey: "name",
        labelVal: "id",
        method: "post",
        resUrl: "rows",
      },
    },
    {
      type: "date",
      prop: "transactionTime",
      label: "交易时间",
      disabled: true,
    },
    // {
    //   type: "selectInput",
    //   label: "交易金额",
    //   itemWidth: 60,
    //   data: accountCurrency.value,
    //   placeholder: "请输入",
    //   selectPlaceholder: "币种",
    //   selectProp: "currency",
    //   prop: "amount",
    //   disabled: true,
    // },
    {
      type: "slot",
      prop: "money",
      slotName: "money",
      label: "交易金额",
    },
    {
      type: "input",
      prop: "remarks",
      label: "摘要",
      disabled: true,
      itemType: "textarea",
      disabled: true,
    },
    {
      type: "slot",
      label: "拆分明细",
      slotName: "slot",
    },
  ];
});
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy
    .post("/accountDeptRunningWater/page", sourceList.value.pagination)
    .then((message) => {
      sourceList.value.data = message.rows;
      sourceList.value.pagination.total = message.total;
      setTimeout(() => {
        loading.value = false;
      }, 200);
    });
};
proxy.getDict(["account_currency"]).then((res) => {
  accountCurrency.value = res.account_currency.map((item) => {
    return {
      label: item.dictValue,
      value: item.dictKey,
    };
  });
});
const submitForm = async () => {
  submit.value.handleSubmit(() => {
    if (
      !(
        formData.data.accountDeptRunningWaterDetailList &&
        formData.data.accountDeptRunningWaterDetailList.length > 0
      )
    ) {
      return ElMessage("请添加拆分明细!");
    }
    let money = 0;
    for (
      let i = 0;
      i < formData.data.accountDeptRunningWaterDetailList.length;
      i++
    ) {
      if (
        formData.data.accountDeptRunningWaterDetailList[i].amount &&
        Number(formData.data.accountDeptRunningWaterDetailList[i].amount) !== 0
      ) {
        money = Number(
          parseFloat(
            Number(money) +
              Number(formData.data.accountDeptRunningWaterDetailList[i].amount)
          )
        );
      } else {
        return ElMessage("金额不能为0");
      }
    }
    if (Number(money) !== Number(formData.data.amount)) {
      return ElMessage("分拆总金额需等于交易金额");
    }
    submitLoading.value = true;
    const params = {
      id: formData.data.id,
      deptRunningWaterDetailList:
        formData.data.accountDeptRunningWaterDetailList,
      accountDeptRunningWaterId: formData.data.accountDeptRunningWaterId,
    };
    params.deptRunningWaterDetailList.map((item) => {
      item.deptId = item.deptId[item.deptId.length - 1];
    });
    proxy
      .post("/accountDeptRunningWaterDetail/add", {
        ...params,
      })
      .then(
        () => {
          ElMessage({
            message: "拆分成功",
            type: "success",
          });
          dialogVisible.value = false;
          submitLoading.value = false;
          getList();
        },
        (err) => (submitLoading.value = false)
      );
  });
};
const getDtl = (row) => {
  modalType.value = "edit";
  dialogVisible.value = true;
  proxy
    .post("/accountDeptRunningWaterDetail/detail", { id: row.id })
    .then((res) => {
      if (
        res.deptRunningWaterDetailList &&
        res.deptRunningWaterDetailList.length > 0
      ) {
        res.accountDeptRunningWaterDetailList =
          res.deptRunningWaterDetailList.map((item) => {
            item.deptId = [item.deptId];
            return item;
          });
      } else {
        res.accountDeptRunningWaterDetailList = [];
      }
      formData.data = res;
      dialogVisible.value = true;
    });
};
const addRow = () => {
  formData.data.accountDeptRunningWaterDetailList.push({
    remarks: "",
    amount: null,
    deptId: [],
  });
};
const handleRemove = (index) => {
  formData.data.accountDeptRunningWaterDetailList.splice(index, 1);
  return ElMessage({
    message: "删除成功！",
    type: "success",
  });
};
getList();
</script>

<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
::v-deep(.el-input-number .el-input__inner) {
  text-align: left;
}
</style>
