<template>
  <div class="tenant">
    <!-- <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.amount <= 0 ? 'red' : '#39C55A'}`">
            {{dictDataEcho(item.currency,dictsData.account_currency) + ' ' + item.amount}}
          </div>
        </template>
        
      </byTable>
    </div>
    <el-dialog
      title="拆分"
      v-model="dialogVisible"
      width="600"
      v-loading="loading"
    >
      <byForm
        :formConfig="formConfig"
        :formOption="formOption"
        v-model="formData.data"
        :rules="rules"
        ref="byform"
      >
        <template #slot>
          <div style="width: 100%">
            <el-button type="primary" @click="addRow"> 添加 </el-button>
            <el-form
              ref="tableForm"
              :model="formData.data"
              :rules="rules"
              label-width="0px"
              style="margin-top: 15px"
            >
              <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
                        v-model="row.amount"
                        placeholder="请输入"
                        type="number"
                      />
                    </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" label="操作" width="100">
                  <template #default="{ $index }">
                    <el-button type="primary" link @click="handleRemove($index)"
                      >删除</el-button
                    >
                  </template>
                </el-table-column>
              </el-table>
            </el-form>
          </div>
        </template>
      </byForm>
      <template #footer>
        <el-button @click="dialogVisible = false" size="large">取 消</el-button>
        <el-button
          type="primary"
          @click="submitForm('byform')"
          size="large"
          :loading="submitLoading"
        >
          确 定
        </el-button>
      </template>
    </el-dialog>
    <el-dialog
      title="调整部门"
      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="large">取 消</el-button>
        <el-button
          type="primary"
          @click="submitDeptForm(departmentId)"
          size="large"
          :loading="submitLoading"
        >
          确 定
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>
  
<script setup>
/* eslint-disable vue/no-unused-components */
import { ElMessage, ElMessageBox } from "element-plus";
import byTable from "@/components/byTable/index";
import byForm from "@/components/byForm/index";
import { computed, defineComponent, ref } from "vue";
import useUserStore from "@/store/modules/user";

const loading = ref(false);
const submitLoading = ref(false);
const sourceList = ref({
  data: [],
  pagination: {
    total: 3,
    pageNum: 1,
    pageSize: 10,
  },
});
let dialogVisible = ref(false);
let roomDialogVisible = ref(false);
let modalType = ref("add");
let rules = ref({
  type: [{ required: true, message: "请选择类型", trigger: "change" }],
  contactNumber: [
    { required: true, message: "请输入联系号码", trigger: "blur" },
  ],
});
import Cookies from 'js-cookie'

const { proxy } = getCurrentInstance();
const selectConfig = [];
const config = computed(() => {
  return [
    {
      attrs: {
        label: "资金账户",
        prop: "accountManagementName",
      },
    },
    {
      attrs: {
        label: "交易时间",
        prop: "transactionTime",
      },
    },
    {
      attrs: {
        label: "交易金额",
        prop: "amount",
        slot:'amount'
      },
    },
    {
      attrs: {
        prop: "accountOpening",
        label: "对方账户",
      },
    },
    {
      attrs: {
        prop: "openingBank",
        label: "对方银行",
      },
    },
    {
      attrs: {
        prop: "name",
        label: "对方账号",
      },
    },
    {
      attrs: {
        prop: "remarks",
        label: "摘要",
      },
    },
    {
      attrs: {
        label: "操作",
        width: "200",
        align: "right",
      },
      // 渲染 el-button，一般用在最后一列。
      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 byform = ref(null);
const treeData = ref([]);
const depModal = ref(false);
let deptTreeData = ref([]);
let departmentId = ref([])
let runningWaterId = ''
const getDept = async (row) => {
  // 部门树
  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((message) => {
      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:[],
      placeholder: "请输入",
      selectPlaceholder: "币种",
      selectProp: "currency",
      prop: "amount",
      disabled: true,
    },
    {
      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) => {
      console.log(message)
      sourceList.value.data = message.rows;
      sourceList.value.pagination.total = message.total;
      setTimeout(() => {
        loading.value = false;
      }, 200);
    });
};
let dictsData = reactive({})
proxy
	.getDict(['payment_status','account_currency'])
	.then((res) => {
		dictsData = res
		formConfig.value[2].data = res.account_currency.map(item => {
			return {
				label: item.dictValue,
				value: item.dictKey,
			}
		})
	})


const openModal = () => {
  dialogVisible.value = true;
  modalType.value = "add";
  formData.data = {};
};


const submitForm = () => {
  byform.value.handleSubmit((valid) => {
    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(
      (res) => {
        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) => {
      console.log(res)
      res.accountDeptRunningWaterDetailList = res.deptRunningWaterDetailList.map((item) => {
        item.deptId = [item.deptId];
        return item;
      });
      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",
  });
};

const contactInformationType = ref([]);

const getTypeData = (item, type) => {
  if (item.accountDeptRunningWaterDetailList)
    return item.accountDeptRunningWaterDetailList.filter((x) => x.type === type) || [];
};

getList();

</script>
  
<style lang="scss" scoped>
.tenant {
  padding: 20px;
}
</style>