<template>
  <div>
    <xy-dialog ref="dialog" :is-show.sync="isShow" type="normal" title="出差报销审批" @on-ok="confirm">
      <xy-table ref="awayTable" row-key="id" default-expand-all
        :tree-props="{children: 'children', hasChildren: 'hasChildren'}" :table-item="table" @select-all="toggleAll"
        @select="handleSelectionChange" :list="chuchaibaoxiaoDetailList">
        <template v-slot:oa_ht_away_links>
          <el-table-column prop="oa_ht_away_links" align="center" label="状态" width="100">
            <template #default="scope">
              <div v-if="scope.row.hasOwnProperty('oa_ht_away_links')">
                <el-tag v-if="scope.row.oa_ht_away_links" type="success" size="small">
                  已完成
                </el-tag>
                <el-tag v-else type="warning" size="small">
                  待审批
                </el-tag>
              </div>

            </template>
          </el-table-column>
        </template>
        <template #btns> </template>
      </xy-table>
    </xy-dialog>
  </div>
</template>

<script>
  import {
    getBudget
  } from "@/api/budget/budget";
  import {
    addFundLog
  } from "@/api/paymentRegistration/fundLog";
  import {
    save,
    getAwayDetails,
    updateAwayDetails,
    planSave
  } from "@/api/away";

  export default {
    data() {
      return {
        isShow: false,
        checkdKeys: false,
        table: [{
            type: 'selection',
            width: 54,
            reserveSelection: true,
            fixed: "left",
            selectable: row => row.oa_ht_away_links ? false : true,
          },
          {
            prop: 'name',
            label: '人员',
            width: 120,
            align: 'left'
          },
          {
            prop: 'zijinlaiyuan',
            label: '资金来源',
            minWidth: 240,
            align: 'left'
          },
          {
            prop: 'flow.title',
            label: '流程名称',
            minWidth: 240,
            align: 'left'
          },
          {
            prop: 'amt',
            label: '报销金额',
            width: 120,
            align: 'center'
          },
          {
            prop: 'oa_ht_away_links',
            label: '状态',
            width: 180,
            align: 'center'
          },
          {
            prop: 'remark',
            label: '备注',
            align: 'left'
          }, {
            label: "创建日期",
            width: 160,
            prop: "created_at",
            formatter: (cell, data, value) => {
              return this.$moment(value).format("YYYY-MM-DD HH:mm");
            },
          },
        ],
        records: [],
        plans: [],
        chuchaibaoxiaoDetailList: [],
        away_ids: []
      };
    },
    computed: {

    },
    methods: {
      show() {
        this.isShow = true;
      },
      hidden() {
        this.chuchaibaoxiaoDetailList = [];
        this.away_ids = [];
        this.$refs['awayTable'].clearSelection();
        this.isShow = false;
      },
      setRecords(ids) {
        console.log("ids", ids);
        this.getAway(ids);
      },
      async getAway(ids) {
        this.away_ids = ids;
        let res = await getAwayDetails({
          away_ids: ids
        });
        console.log("res.chuchaibaoxiaoDetailList", res.chuchaibaoxiaoDetailList)
        let arr = this.transformData(res.chuchaibaoxiaoDetailList)
        console.log("arr", arr);
        this.chuchaibaoxiaoDetailList = arr;
        this.$refs.awayTable.clearSelection()
      },
      transformData(originalData) {
        const result = [];
        for (const xingming_details in originalData) {
          const person = {
            id: Math.random(),
            name: xingming_details,
            children: [],
            parent: null, // 添加父级字段
            isSelect: false // 添加选中状态字段
          };
          const innerData = originalData[xingming_details];
          innerData.map(item => {
            item.isSelect = false
          })
          person.children.push(...innerData)
          // const source = {
          //   id: Math.random(),
          //   name: '',
          //   children: innerData.map((item) => ({
          //     ...item,
          //     name: item.xingming_detail,
          //     parent: source, // 指向当前父级
          //     isSelect: false // 添加选中状态字段
          //   })),
          //   parent: person, // 指向当前父级
          //   isSelect: false // 添加选中状态字段
          // };
          // person.children.push(source);

          result.push(person);
        }
        return result;
      },
      toggleAll() {
        this.checkdKeys = !this.checkdKeys
        this.splite(this.chuchaibaoxiaoDetailList, this.checkdKeys)

      },
      splite(data, flag) {
        data.forEach((row) => {
          this.$refs.awayTable.toggleRowSelection(row, flag)
          if (row.children) {
            this.splite(row.children, flag)
          }
        })
      },
      handleSelectionChange(selection, row) {
        const allData = this.chuchaibaoxiaoDetailList;

        // 取消选择的逻辑
        row.isSelect = !row.isSelect
        console.log("selection", selection, row)
        this.deselectChildren(row, row.isSelect); // 递归取消选择所有子级

        // if(!row.isSelect){
        //   this.deselectChildren(row,row.isSelect); // 递归取消选择所有子级
        //   // this.updateParentSelection(row, true); // 更新父级状态
        // }else{
        //   // 选择的逻辑
        //   selection.forEach((item) => {
        //     if (!this.isSelected(item)) {
        //       this.selectChildren(item); // 递归选中所有子级
        //       // this.updateParentSelection(item, true); // 更新父级状态
        //     }
        //   });
        // }

      },
      selectChildren(parent) {
        if (parent.children) {
          parent.children.forEach((child) => {
            this.$refs.awayTable.toggleRowSelection(child, true); // 选中当前子级
            // child.isSelect = true; // 更新子级的 isSelect 状态
            this.$set(child, 'isSelect', true)
            this.selectChildren(child); // 递归选中子级的子级
          });
        }
      },
      deselectChildren(parent, isSelect) {
        console.log("isSelect", isSelect, parent)
        if (parent.children) {
          parent.children.forEach((child, index) => {
            this.$refs.awayTable.toggleRowSelection(child, isSelect); // 取消选择当前子级
            this.$set(child, 'isSelect', isSelect)
            this.deselectChildren(child, isSelect); // 递归取消选择子级的子级
          });
        } else {
          this.$refs.awayTable.toggleRowSelection(parent, isSelect);
          this.$set(parent, 'isSelect', isSelect)
          console.log("parent", parent)
        }
      },
      // updateParentSelection(item, isSelected) {
      //   if (item.parent) {
      //     const allSelected = item.parent.children.every((child) => child.isSelect === true);
      //     const anySelected = item.parent.children.some((child) => child.isSelect === true);
      //     item.parent.isSelect = allSelected ? true : anySelected ? '' : false; // 全选、半选、不选
      //     this.$refs.awayTable.toggleRowSelection(item.parent, allSelected);
      //     this.updateParentSelection(item.parent, allSelected); // 递归更新父级
      //   }
      // },
      isSelected(item) {
        return item.isSelect === true;
      },
      async getBudgets() {
        let res = await getBudget({
          is_tree: 1
        });
        this.plans = res.list;
      },
      async confirm() {
        console.log("this.$refs['awayTable'].getSelection()", this.$refs['awayTable'].getSelection());
        let flowsList = this.$refs['awayTable'].getSelection();

        let flow_id = [];
        let chuchai_pay_id = [];
        let chuchai_pay_details = [];
        let person_arr = []
        let plan_moneys = []
        let away_ids_arr = []
        let money = 0
        flowsList.map(f => {
          if (f.flow && !f.oa_ht_away_links) {
            person_arr.push(f)
          }
        });
        if (person_arr.length < 1) {
          this.$message.warning('请选择待审批的出差报销')
          return
        }
        console.log("person_arr",person_arr)
        person_arr.map(item => {
          flow_id.push(item.flow.id);
          chuchai_pay_id.push(item.belongs_id);
          chuchai_pay_details.push(item.id);
          away_ids_arr.push(item.flow.out_away_id)
          plan_moneys.push({
            plan_id:item.plan_id,
            money:item.amt,
            away_id:item.flow.out_away_id
          })
          money += parseFloat(item.amt)
        })
        // away/save
        const away_plan_links = [];
        const planMap = {};

        person_arr.forEach(item => {
          const {
            id,
            plan_id,
            amt,
          } = item;
          if (!planMap[plan_id]) {
            planMap[plan_id] = {
              plan_id,
              use_money: 0,
              chuchai_pay_details: []
            };
            away_plan_links.push(planMap[plan_id]);
          }
          planMap[plan_id].use_money += parseFloat(amt);
          planMap[plan_id].chuchai_pay_details.push(id);
        });
        console.log("away_plan_links", plan_moneys,away_plan_links)
        // return
        const res = await updateAwayDetails({
          away_ids: away_ids_arr,
          flow_id: flow_id,
          chuchai_pay_id: chuchai_pay_id,
          chuchai_pay_details: chuchai_pay_details,
          money: money,
          plan_money:plan_moneys
        }, true);
        console.log("res", res)
        await Promise.allSettled(away_plan_links.map((i, index) => {
          console.log(i)
          planSave({
            plan_id: i.plan_id,
            use_money: i.use_money,
            chuchai_pay_details: i.chuchai_pay_details
          })
        }))
        this.$message.success('操作成功');
        this.$emit('refresh');
        this.hidden();
      }
    },

    created() {
      // this.getBudgets()
    }
  };
</script>

<style scoped lang="scss">
</style>
