<template>
  <div class="pageIndexClass">
    <byTable :source="sourceList.data" :pagination="sourceList.pagination" :config="config" :loading="loading" :selectConfig="selectConfig"
             highlight-current-row :action-list="[
        {
          text: '往来单位',
          action: () => addUnit(),
          type: ' ',
        },
        {
          text: '添加往来',
          action: () => addModal(),
        },
      ]" @get-list="getList">
      <template #amount="{ item }">
        <div>
          <span style="padding-right: 4px">{{ item.currency }}</span>
          <span>{{ moneyFormat(item.amount, 2) }}</span>
        </div>
      </template>
    </byTable>

    <el-dialog title="往来单位" v-if="openUnit" v-model="openUnit" width="700">
      <div style="width: 100%">
        <el-button @click="clickAddUnit">添 加</el-button>
        <el-table :data="departmentList" style="margin-top: 20px">
          <el-table-column label="单位名称" prop="name" width="220" />
          <el-table-column label="备注" prop="remark" />
          <el-table-column label="操作" align="center" width="120" fixed="right">
            <template #default="{ row }">
              <el-button type="primary" link @click="handleUpdate(row)">修改</el-button>
              <el-button type="primary" link @click="handleDelete(row)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <template #footer>
        <el-button @click="openUnit = false" size="default">关 闭</el-button>
      </template>
    </el-dialog>

    <el-dialog :title="modalType == 'add' ? '添加单位' : '编辑单位'" v-if="openAddUnit" v-model="openAddUnit" width="400">
      <byForm :formConfig="formUnitConfig" :formOption="formOption" v-model="formUnitData.data" :rules="rulesUnit" ref="unit"></byForm>
      <template #footer>
        <el-button @click="openAddUnit = false" size="default">关 闭</el-button>
        <el-button type="primary" @click="submitUnitForm()" size="default">确 定</el-button>
      </template>
    </el-dialog>

    <el-dialog title="添加往来" v-if="openComeAndGo" v-model="openComeAndGo" width="500">
      <byForm :formConfig="formConfig" :formOption="formOption" v-model="formData.data" :rules="rules" ref="comeAndGo">
        <template #amount>
          <div style="width: 100%">
            <el-form-item prop="amount">
              <el-select v-model="formData.data.currency" placeholder="请选择币种" style="width: 100px">
                <el-option v-for="item in accountCurrency" :key="item.value" :label="item.value" :value="item.value" />
              </el-select>
              <el-input-number onmousewheel="return false;" v-model="formData.data.amount" placeholder="请输入金额" style="width: calc(100% - 100px)"
                               :precision="2" :controls="false" :min="0" />
            </el-form-item>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="openComeAndGo = false" size="default">关 闭</el-button>
        <el-button type="primary" @click="submitForm()" size="default">确 定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

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

const { proxy } = getCurrentInstance();
const loading = ref(false);
const accountCurrency = ref([]);
const accountList = ref([]);
const departmentList = ref([]);
const isFlowingWater = ref([
  {
    label: "是",
    value: "1",
  },
  {
    label: "否",
    value: "0",
  },
]);
const type = ref([
  {
    label: "收入",
    value: "0",
  },
  {
    label: "支出",
    value: "1",
  },
]);
const sourceList = ref({
  data: [],
  pagination: {
    total: 0,
    pageNum: 1,
    pageSize: 10,
    keyword: "",
    isFlowingWater: "",
    departmentId: "",
    type: "",
  },
});
const selectConfig = computed(() => {
  return [
    {
      label: "是否流水",
      prop: "isFlowingWater",
      data: isFlowingWater.value,
    },
    {
      label: "往来单位",
      prop: "departmentId",
      data: departmentList.value,
    },
    {
      label: "往来类型",
      prop: "type",
      data: type.value,
    },
  ];
});
const config = computed(() => {
  return [
    {
      attrs: {
        label: "往来单位",
        prop: "departmentId",
        "min-width": 180,
      },
      render(val) {
        return proxy.dictValueLabel(val, departmentList.value);
      },
    },
    {
      attrs: {
        label: "往来类型",
        prop: "type",
        width: 140,
      },
      render(val) {
        return proxy.dictValueLabel(val, type.value);
      },
    },
    {
      attrs: {
        label: "往来金额",
        slot: "amount",
        width: 140,
      },
    },
    {
      attrs: {
        label: "是否流水",
        prop: "isFlowingWater",
        width: 140,
      },
      render(val) {
        return proxy.dictValueLabel(val, isFlowingWater.value);
      },
    },
    {
      attrs: {
        label: "往来账户",
        prop: "accountId",
        "min-width": 180,
      },
      render(val) {
        return proxy.dictValueLabel(val, accountList.value);
      },
    },
    {
      attrs: {
        label: "备注",
        prop: "remark",
        "min-width": 240,
      },
    },
  ];
});
const getDict = () => {
  proxy.getDictOne(["account_currency"]).then((res) => {
    if (res["account_currency"] && res["account_currency"].length > 0) {
      accountCurrency.value = res["account_currency"].map((x) => ({
        label: x.dictValue,
        value: x.dictKey,
      }));
    }
  });
  proxy
    .post("/accountManagement/page", { pageNum: 1, pageSize: 9999 })
    .then((res) => {
      if (res.rows && res.rows.length > 0) {
        accountList.value = res.rows.map((item) => {
          return {
            ...item,
            label: item.alias + " (" + item.accountOpening + ")",
            value: item.id,
          };
        });
      }
    });
  getDepartmentList();
};
const getDepartmentList = () => {
  proxy
    .get("/transactionDepartment/list", { pageNum: 1, pageSize: 999 })
    .then((res) => {
      if (res.data && res.data.length > 0) {
        departmentList.value = res.data.map((item) => {
          return {
            ...item,
            label: item.name,
            value: item.id,
          };
        });
      } else {
        departmentList.value = [];
      }
    });
};
const getList = async (req) => {
  sourceList.value.pagination = { ...sourceList.value.pagination, ...req };
  loading.value = true;
  proxy.post("/transaction/page", sourceList.value.pagination).then((res) => {
    sourceList.value.data = res.rows;
    sourceList.value.pagination.total = res.total;
    setTimeout(() => {
      loading.value = false;
    }, 200);
  });
};
getDict();
getList();
const openComeAndGo = ref(false);
const formData = reactive({
  data: {
    departmentId: "",
    type: "",
    currency: "",
    amount: undefined,
    isFlowingWater: "",
    accountId: "",
    remark: "",
  },
});
const comeAndGo = ref(null);
const formConfig = computed(() => {
  return [
    {
      type: "select",
      prop: "departmentId",
      label: "往来单位",
      data: departmentList.value,
    },
    {
      type: "select",
      prop: "type",
      label: "往来类型",
      data: type.value,
    },
    {
      type: "select",
      prop: "isFlowingWater",
      label: "是否流水",
      data: isFlowingWater.value,
    },
    {
      type: "select",
      prop: "accountId",
      label: "往来账户",
      data: accountList.value,
    },
    {
      type: "slot",
      slotName: "amount",
      prop: "amount",
      label: "往来金额",
    },
    {
      type: "input",
      prop: "remark",
      label: "备注",
      itemType: "textarea",
    },
  ];
});
const rules = computed(() => {
  return {
    departmentId: [
      { required: true, message: "请选择往来单位", trigger: "change" },
    ],
    type: [{ required: true, message: "请选择往来类型", trigger: "change" }],
    isFlowingWater: [
      { required: true, message: "请选择是否流水", trigger: "change" },
    ],
    accountId: [
      {
        required: formData.data.isFlowingWater === "1" ? true : false,
        message: "请选择往来账户",
        trigger: "change",
      },
    ],
    amount: [{ required: true, message: "请输入往来金额", trigger: "blur" }],
  };
});
const addModal = () => {
  formData.data = {
    departmentId: "",
    type: "",
    currency: "",
    amount: undefined,
    isFlowingWater: "0",
    accountId: "",
    remark: "",
  };
  if (accountCurrency.value && accountCurrency.value.length > 0) {
    formData.data.currency = accountCurrency.value[0].value;
  }
  openComeAndGo.value = true;
};
const submitForm = () => {
  comeAndGo.value.handleSubmit(() => {
    proxy.post("/transaction/add", formData.data).then(() => {
      ElMessage({
        message: "添加成功",
        type: "success",
      });
      openComeAndGo.value = false;
      getList();
    });
  });
};
const openUnit = ref(false);
const addUnit = () => {
  openUnit.value = true;
};
const handleDelete = (row) => {
  ElMessageBox.confirm("此操作将永久删除该数据, 是否继续?", "提示", {
    confirmButtonText: "确定",
    cancelButtonText: "取消",
    type: "warning",
  }).then(() => {
    proxy.post("/transactionDepartment/delete", { id: row.id }).then(() => {
      ElMessage({
        message: "删除成功",
        type: "success",
      });
      getDepartmentList();
    });
  });
};
const modalType = ref("add");
const openAddUnit = ref(false);
const formUnitData = reactive({
  data: {
    name: "",
    remark: "",
  },
});
const unit = ref(null);
const formOption = reactive({
  inline: true,
  labelWidth: 100,
  itemWidth: 100,
  rules: [],
});
const formUnitConfig = computed(() => {
  return [
    {
      type: "input",
      prop: "name",
      label: "单位名称",
      itemType: "text",
    },
    {
      type: "input",
      prop: "remark",
      label: "备注",
      itemType: "textarea",
    },
  ];
});
const rulesUnit = ref({
  name: [{ required: true, message: "请输入单位名称", trigger: "blur" }],
});
const clickAddUnit = () => {
  modalType.value = "add";
  formUnitData.data = {
    name: "",
    remark: "",
  };
  openAddUnit.value = true;
};
const submitUnitForm = () => {
  unit.value.handleSubmit(() => {
    proxy
      .post("/transactionDepartment/" + modalType.value, formUnitData.data)
      .then(() => {
        ElMessage({
          message: modalType.value == "add" ? "添加成功" : "编辑成功",
          type: "success",
        });
        openAddUnit.value = false;
        getDepartmentList();
      });
  });
};
const handleUpdate = (row) => {
  modalType.value = "edit";
  formUnitData.data = proxy.deepClone(row);
  openAddUnit.value = true;
};
</script>

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