<template>
  <div style="padding: 0 20px">
    <lx-header
      icon="md-apps"
      style="margin-bottom: 10px; border: 0px; margin-top: 15px"
      text="预算计划"
    >
      <div slot="content"></div>
      <slot>
        <div>
          <span style="padding: 0 6px">名称</span>
          <span><el-input
            v-model="select.name"
            placeholder="请输入名称"
            style="width: 130px"
            size="small"
          ></el-input></span>
          <span style="padding: 0 6px">年份</span>
          <span>
            <DatePicker
              :value="select.year"
              placeholder="选择所属年份"
              placement="bottom"
              style="width: 130px"
              type="year"
              :clearable="false"
              @on-change="(e) => (select.year = e)"
            ></DatePicker>
          </span>

          <span style="padding: 0 6px">资金隶属情况</span>
          <span>
            <el-select
              placeholder="资金隶属情况"
              clearable
              multiple
              collapse-tags
              size="small"
              v-model="select.dimension"
              style="width: 200px"
            >
              <el-option
                v-for="item in dimensions"
                :label="item.value"
                :value="item.id"
                :key="item.id"
              >
              </el-option>
            </el-select>
          </span>


          <span style="padding: 0 6px"> 预算类型 </span>
          <span>
             <el-cascader
               :options="types"
               :props="{
                checkStrictly: true,
                label: 'name',
                value: 'id',
              }"
               :value="select.type"
               clearable
               size="small"
               style="width: 200px"
               @change="handleTypePick"
             />
          </span>

          <span style="padding: 0 6px"> 科室 </span>
          <span>
            <el-select
              placeholder="科室选择"
              clearable
              size="small"
              v-model="select.department"
              style="width: 160px"
            >
              <el-option
                v-for="item in departments"
                :label="item.name"
                :value="item.id"
                :key="item.id"
              >
              </el-option>
            </el-select>
          </span>
          <el-switch
            v-model="isTree"
            @change="changeTree"
            active-text="树形结构"
            style="margin-left: 4px"
          >
          </el-switch>
          <Button style="margin-left: 10px" type="primary" @click="showAdd('')"
            >新增</Button
          >
          <Button style="margin-left: 10px" type="primary" @click="getBudgets"
            >查询</Button
          >
          <Button
            style="margin-left: 10px"
            type="primary"
            @click="
              () => (select = { page: 1, year: '', type: '', department: '' })
            "
            >重置
          </Button>
        </div>
      </slot>
    </lx-header>

    <div v-if="isTree">
      <el-table
        stripe
        ref="treeTable"
        :height="tableHeight"
        class="v-table"
        :summary-method="summary"
        show-summary
        :data="treeData"
        style="width: 100%; margin-bottom: 20px"
        row-key="id"
        border
        default-expand-all
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
      >
        <el-table-column
          type="index"
          align="center"
          fixed="left"
        ></el-table-column>
        <el-table-column
          v-for="(item, index) of table"
          :prop="item.prop"
          :label="item.label"
          :width="item.width"
          :min-width="item.minWidth"
          :fixed="item.fixed"
          :align="item.align"
          :formatter="item.formatter"
        >
<!--          <template slot-scope="scope">-->
<!--            <span v-if="item.formatter">-->
<!--              {{ item.formatter(scope.row, scope.row, scope.row[item.prop]) }}-->
<!--            </span>-->
<!--            <span v-else>-->
<!--              {{-->
<!--                item.prop.indexOf(".") > -1-->
<!--                  ? scope.row[item.prop.split(".")[0]][item.prop.split(".")[1]]-->
<!--                  : scope.row[item.prop]-->
<!--              }}-->
<!--            </span>-->
<!--          </template>-->
        </el-table-column>
        <el-table-column
          fixed="right"
          header-align="center"
          label="操作"
          width="220"
        >
          <template slot-scope="scope">
            <div class="slot-btns">
<!--              <Tag color="blue" v-if="scope.row.pid === 0">分值：{{ pScore(scope.row) }}</Tag>-->
              <Button
                class="slot-btns-item"
                size="small"
                type="primary"
                @click="showEditor(scope.row)"
              >
                编辑
              </Button>
              <Button
                @click="showAdd(scope.row)"
                v-if="scope.row.pid == 0"
                class="slot-btns-item"
                size="small"
                type="info"
              >
                下级
              </Button>
              <Poptip
                :transfer="true"
                confirm
                placement="bottom"
                title="确认要删除吗"
                @on-ok="() => deleteTable(scope.row)"
              >
                <i-button class="slot-btns-item" size="small" type="error"
                  >删除
                </i-button>
              </Poptip>
              <Button
                v-if="scope.row.pid == 0"
                class="slot-btns-item"
                size="small"
                type="primary"
                @click="
                $refs['addPoint'].setPlanPid(scope.row.pid),
                  $refs['addPoint'].setPlanId(scope.row.id),
                  $refs['addPoint'].setYear(select.year)
                  $refs['addPoint'].show()
                "
                >绩效指标</Button
              >
              <Button
                v-if="scope.row.pid == 0"
                size="small"
                type="primary"
                class="slot-btns-item"
                @click="
                  () => {
                    $refs['addEvaluate'].setId(scope.row.id);
                    $refs['addEvaluate'].show();
                  }
                "
              >
                绩效目标
              </Button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div v-if="!isTree">
      <xy-table
        stripe
        ref="xyTable"
        :objectSpanMethod="objectSpanMethod"
        :list="list"
        :show-summary="true"
        :summary-method="summary"
        :table-item="table"
        @delete="deleteTable"
        @editor="showEditor"
      >
        <template v-slot:btns>
          <el-table-column
            fixed="right"
            header-align="center"
            label="操作"
            width="200"
          >
            <template slot-scope="scope">
              <div class="slot-btns">
<!--                <Tag color="blue" v-if="scope.row.pid === 0">分值：{{ pScore(scope.row) }}</Tag>-->
                <Button
                  class="slot-btns-item"
                  size="small"
                  type="primary"
                  @click="showEditor(scope.row)"
                >
                  编辑
                </Button>
                <Button
                  @click="showAdd(scope.row)"
                  v-if="scope.row.pid == 0"
                  class="slot-btns-item"
                  size="small"
                  type="info"
                >
                  下级
                </Button>
                <Poptip
                  :transfer="true"
                  confirm
                  placement="bottom"
                  title="确认要删除吗"
                  @on-ok="() => deleteTable(scope.row)"
                >
                  <i-button class="slot-btns-item" size="small" type="error"
                    >删除</i-button
                  >
                </Poptip>
                <Button
                  v-if="scope.row.pid == 0"
                  class="slot-btns-item"
                  size="small"
                  type="primary"
                  @click="
                $refs['addPoint'].setPlanPid(scope.row.pid),
                  $refs['addPoint'].setPlanId(scope.row.id),
                  $refs['addPoint'].setYear(select.year)
                    $refs['addPoint'].show()
                "
                >绩效指标</Button
                >
                <Button
                  v-if="scope.row.pid == 0"
                  class="slot-btns-item"
                  size="small"
                  type="primary"
                  @click="
                   $refs['addPoint'].setPlanPid(scope.row.pid),
                    $refs['addPoint'].setPlanId(scope.row.id),
                      $refs['addPoint'].show()
                  "
                  >绩效目标</Button
                >
              </div>
            </template>
          </el-table-column>
        </template>
      </xy-table>

      <div style="display: flex; justify-content: flex-end">
        <Page
          :total="total"
          show-elevator
          @on-change="pageChange"
          show-sizer
          @on-page-size-change="pageSizeChange"
        />
      </div>
    </div>
    <!--    新增-->
    <xy-dialog
      ref="addBudget"
      :form="form"
      :is-show.sync="isShowAdd"
      :rules="rules"
      title="新增计划"
      type="form"
      @submit="submit"
    >
      <template v-slot:pid v-if="form.pid_info">
        <div class="xy-table-item">
          <div class="xy-table-item-label">隶属</div>
          <div class="xy-table-item-content">
            <div style="width: 300px">
              {{ form.pid_info ? form.pid_info.name : "无" }}
            </div>
          </div>
        </div>
      </template>
      <template v-slot:name>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >项目名称
          </div>
          <div class="xy-table-item-content">
            <el-input
              v-model="form.name"
              clearable
              placeholder="请填写项目名称"
              style="width: 300px"
            />
          </div>
        </div>
      </template>
      <template v-slot:type>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >预算类型
          </div>
          <div class="xy-table-item-content">
            <el-cascader
              :options="types"
              :props="{
                checkStrictly: false,
                label: 'name',
                value: 'id',
              }"
              :value="form.type"
              clearable
              size="small"
              style="width: 300px"
              @change="cascaderPick"
            />
<!--            <el-select-->
<!--              v-model="form.type"-->
<!--              clearable-->
<!--              placeholder="请选择预算类型"-->
<!--              style="width: 300px"-->
<!--            >-->
<!--              <el-option-->
<!--                v-for="item in types"-->
<!--                :label="item.value"-->
<!--                :value="item.id"-->
<!--              ></el-option>-->
<!--            </el-select>-->
          </div>
        </div>
      </template>
      <template #dimension>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            资金隶属维度
          </div>
          <div class="xy-table-item-content">
            <el-select
              placeholder="隶属维度选择"
              clearable
              size="small"
              v-model="form.dimension"
              style="width: 300px"
            >
              <el-option
                v-for="item in dimensions"
                :label="item.value"
                :value="item.id"
                :key="item.id"
              >
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:year>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >项目所属年份
          </div>
          <div class="xy-table-item-content">
            <el-datePicker
              v-model="form.year"
              clearable
              placeholder="请选择所属年份"
              placement="bottom"
              style="width: 300px"
              type="year"
              value-format="yyyy"
            ></el-datePicker>
          </div>
        </div>
      </template>
      <template v-slot:department>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >科室
          </div>
          <div class="xy-table-item-content">
            <el-select
              placeholder="科室选择"
              clearable
              size="small"
              v-model="form.department"
              style="width: 300px"
            >
              <el-option
                v-for="item in departments"
                :label="item.name"
                :value="item.id"
                :key="item.id"
              >
              </el-option>
            </el-select>
          </div>
        </div>
      </template>

      <template v-slot:plan_department_links>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >可用科室
          </div>
          <div class="xy-table-item-content">
            <el-checkbox-group v-model="form.plan_department_link_id">
              <el-checkbox
                v-for="dept in departments"
                :label="dept.id"
                :key="dept.id"
                >{{ dept.name }}</el-checkbox
              >
            </el-checkbox-group>
          </div>
        </div>
      </template>
      <template v-slot:content>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >内容
          </div>
          <div class="xy-table-item-content">
            <el-input
              v-model="form.content"
              clearable
              placeholder="请填写内容"
              style="width: 300px"
              type="textarea"
            />
          </div>
        </div>
      </template>
      <template v-slot:money>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >金额
          </div>
          <div class="xy-table-item-content xy-table-item-price">
            <el-input
              v-model="form.money"
              clearable
              placeholder="请填写金额"
              style="width: 300px"
              @blur="moneyFormat('money')"
              @focus="moneyRecover('money')"
            />
          </div>
        </div>
      </template>
      <template #is_middle_fund>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            是否年中专项资金
          </div>
          <div class="xy-table-item-content">
            <el-switch v-model="form.is_middle_fund" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否"></el-switch>
          </div>
        </div>
      </template>
      <template #is_join_count>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            是否参与执行率统计
          </div>
          <div class="xy-table-item-content">
            <el-switch v-model="form.is_join_count" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否"></el-switch>
          </div>
        </div>
      </template>
      <template v-slot:remark>
        <div class="xy-table-item">
          <div class="xy-table-item-label">备注</div>
          <div class="xy-table-item-content">
            <el-input
              v-model="form.remark"
              clearable
              placeholder="请填写备注"
              style="width: 300px"
              type="textarea"
            />
          </div>
        </div>
      </template>
    </xy-dialog>

    <!--    编辑-->
    <xy-dialog
      ref="editorDialog"
      :form="editorForm"
      :is-show.sync="isShowEditor"
      :rules="rules"
      title="编辑"
      type="form"
    >
      <template v-slot:name>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >项目名称
          </div>
          <div class="xy-table-item-content">
            <el-input
              v-model="editorForm.name"
              clearable
              placeholder="请填写项目名称"
              style="width: 300px"
            />
          </div>
        </div>
      </template>
      <template v-slot:type>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >预算类型
          </div>
          <div class="xy-table-item-content">
            <el-cascader
              :append-to-body="false"
              :options="types"
              :props="{
                checkStrictly: false,
                label: 'name',
                value: 'id',
              }"
              :value="editorForm.type"
              clearable
              size="small"
              style="width: 300px"
              @change="(e) => (editorForm.type = e[e.length - 1] || '',editorForm.type_pid = e[e.length - 2] || '')"
            />
<!--            <el-select-->
<!--              v-model="editorForm.type"-->
<!--              clearable-->
<!--              placeholder="请选择预算类型"-->
<!--              style="width: 300px"-->
<!--            >-->
<!--              <el-option-->
<!--                v-for="item in types"-->
<!--                :label="item.value"-->
<!--                :value="item.id"-->
<!--              ></el-option>-->
<!--            </el-select>-->
          </div>
        </div>
      </template>
      <template #dimension>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            资金隶属维度
          </div>
          <div class="xy-table-item-content">
            <el-select
              placeholder="隶属维度选择"
              clearable
              size="small"
              v-model="editorForm.dimension"
              style="width: 300px"
            >
              <el-option
                v-for="item in dimensions"
                :label="item.value"
                :value="item.id"
                :key="item.id"
              >
              </el-option>
            </el-select>
          </div>
        </div>
      </template>
      <template v-slot:year>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >项目所属年份
          </div>
          <div class="xy-table-item-content">
            <el-datePicker
              v-model="editorForm.year"
              clearable
              placeholder="请选择所属年份"
              placement="bottom"
              style="width: 300px"
              type="year"
              value-format="yyyy"
            ></el-datePicker>
          </div>
        </div>
      </template>
      <template v-slot:department>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >科室
          </div>
          <div class="xy-table-item-content">
            <el-select
              :popper-append-to-body="false"
              placeholder="科室选择"
              clearable
              size="small"
              v-model="editorForm.department"
              style="width: 300px"
            >
              <el-option
                v-for="item in departments"
                :label="item.name"
                :value="item.id"
                :key="item.id"
              >
              </el-option>
            </el-select>
<!--            <el-cascader-->
<!--              :options="departments"-->
<!--              :props="{ checkStrictly: true, label: 'name', value: 'id' }"-->
<!--              :value="editorForm.department"-->
<!--              clearable-->
<!--              size="small"-->
<!--              style="width: 300px"-->
<!--              @change="(e) => (editorForm.department = e[e.length - 1] || '')"-->
<!--            />-->
          </div>
        </div>
      </template>

      <template v-slot:plan_department_links>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >可用科室
          </div>
          <div class="xy-table-item-content">
            <el-checkbox-group v-model="editorForm.plan_department_link_id">
              <el-checkbox
                v-for="dept in departments"
                :label="dept.id"
                :key="dept.id"
                >{{ dept.name }}</el-checkbox
              >
            </el-checkbox-group>
          </div>
        </div>
      </template>

      <template v-slot:content>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >内容
          </div>
          <div class="xy-table-item-content">
            <el-input
              v-model="editorForm.content"
              autosize
              clearable
              placeholder="请填写内容"
              style="width: 300px"
              type="textarea"
            />
          </div>
        </div>
      </template>
      <template v-slot:money>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >年初预算金额
          </div>
          <div class="xy-table-item-content xy-table-item-price">
            <el-input
              v-model="editorForm.money"
              clearable
              placeholder="请填写年初预算金额"
              style="width: 300px"
              @blur="moneyFormatEditor('money')"
              @focus="moneyRecoverEditor('money')"
            />
          </div>
        </div>
      </template>
      <template v-slot:update_money>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            <span style="color: red; font-weight: 600; padding-right: 4px"
              >*</span
            >调整后预算金额
          </div>
          <div class="xy-table-item-content xy-table-item-price">
            <el-input
              v-model="editorForm.update_money"
              clearable
              placeholder="请填写调整后预算金额"
              style="width: 300px"
              @blur="moneyFormatEditor('update_money')"
              @focus="moneyRecoverEditor('update_money')"
            />
          </div>
        </div>
      </template>
      <template #is_middle_fund>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
           是否年中专项资金
          </div>
          <div class="xy-table-item-content">
            <el-switch v-model="editorForm.is_middle_fund" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否"></el-switch>
          </div>
        </div>
      </template>
      <template #is_join_count>
        <div class="xy-table-item">
          <div class="xy-table-item-label">
            是否参与执行率统计
          </div>
          <div class="xy-table-item-content">
            <el-switch v-model="editorForm.is_join_count" :active-value="1" :inactive-value="0" active-text="是" inactive-text="否"></el-switch>
          </div>
        </div>
      </template>
      <template v-slot:remark>
        <div class="xy-table-item">
          <div class="xy-table-item-label">备注</div>
          <div class="xy-table-item-content">
            <el-input
              v-model="editorForm.remark"
              autosize
              clearable
              placeholder="请填写备注"
              style="width: 300px"
              type="textarea"
            />
          </div>
        </div>
      </template>
      <template v-slot:footerContent>
        <Button type="primary" @click="editorTable">确定</Button>
      </template>
    </xy-dialog>

    <addPoint ref="addPoint"></addPoint>
    <addEvaluate ref="addEvaluate"></addEvaluate>
  </div>
</template>

<script>
import {
  addBudget,
  getBudget,
  delBudget,
  editorBudget,
  detailBudget,
} from "@/api/budget/budget";
import { listdeptNoAuth } from "@/api/system/department";
import { Message } from "element-ui";
import { parseTime, moneyFormatter, moneyRecovery } from "@/utils";
import { getparameter, getparameterTree } from "@/api/system/dictionary";
import { mergeTableRow } from "@/utils/mergeTableRow";

import addPoint from "./components/addPoint.vue";
import addEvaluate from "./components/addEvaluate.vue";
export default {
  components: {
    addPoint,
    addEvaluate,
  },
  data() {
    return {
      tableHeight: 0,
      isShowAdd: false,
      types: [],
      treeData: [],
      isTree: true,
      form: {
        pid: "0",
        dimension: 1,
        name: "",
        type: "",
        year: "",
        department: "",
        money: "",
        is_middle_fund: 1,
        is_join_count: 1,
        content: "",
        remark: "",
        plan_department_link_id: [],
        plan_department_links: [],
        update_money: "",
        pid_info: null,
      },
      rules: {
        name: [
          {
            required: true,
            message: "必填项",
          },
        ],
        type: [
          {
            required: true,
            message: "必选项",
          },
        ],
        year: [
          {
            required: true,
            message: "必选项",
          },
        ],
        department: [
          {
            required: true,
            message: "必选项",
          },
        ],
        money: [
          {
            required: true,
            message: "必填项",
          },
          {
            pattern: /^\d{1,3}(,\d{3})*(\.\d+)/,
            message: "必须为数字",
            trigger: "change",
          },
        ],
        content: [
          {
            required: true,
            message: "必填项",
          },
        ],
      },
      list: [],
      totalMoney: 0,
      updateMoney: 0,
      total: 0,
      pageIndex: 1,
      pageSize: 10,
      table: [],
      tableItem: [
        {
          label: "项目名称",
          prop: "name",
          width: 200,
          align: "left",
          sortable: false,
          fixed: "left",
        },
        {
          prop: 'type_detail.value',
          label: "预算类型",
          width: 115,
        },
        {
          label: "所属年份",
          prop: "year",
          width: 105,
        },
        // {
        //   label: "相关科室",
        //   prop: "plan_department.name",
        //   width: 110,
        // },
        {
          label: "年初预算金额（元）",
          prop: "money",
          align: "right",
          width: 180,
          formatter: (cell, data, value) => {
            if (value == 0) return "--";
            else return moneyFormatter(value);
          },
        },
        {
          label: "调整后预算金额（元）",
          prop: "update_money",
          align: "right",
          width: 200,
          formatter: (cell, data, value) => {
            return moneyFormatter(value);
          },
        },
        {
          label: "创建信息",
          prop: "created_at",
          width: 160,
          formatter: (cell, data, value) => {
            return parseTime(new Date(value), "{y}-{m}-{d}");
          },
        },
        {
          label: '科室',
          width: 150,
          prop: 'plan_department.name'
        },
        {
          label: "描述",
          minWidth: 300,
          prop: "content",
          align: "left",
          sortable: false,
        },
      ],
      select: {
        name: "",
        page: 1,
        year: "",
        type: "",
        department: "",
        is_auth: 0,
        type_pid: "",
        dimension: []
      },
      departments: [], //部门类型
      dimensions: [
        {
          value: "年初部门预算",
          id: "1"
        },
        {
          value: "年中追加部门预算",
          id: "2"
        },
        {
          value: "上年结转资金",
          id: "3"
        },
        {
          value: "基本户资金",
          id: "4"
        },
        {
          value: "其他",
          id: "5"
        }
      ],

      //编辑信息
      isShowEditor: false,
      editorForm: {
        plan_department_link_id: [],
      },
    };
  },
  methods: {
    handleTypePick(e) {
      if (e.length === 1) {
        this.select.type_pid = e[0] || ''
        this.select.type = ''
      }
      else if (e.length === 2) {
        this.select.type_pid = e[1] || ''
        this.select.type = ''
      }
      else if (e.length === 3) {
        this.select.type_pid = ''
        this.select.type = e[e.length - 1] || ''
      } else {
        this.select.type = ''
        this.select.type_pid = ''
      }
      console.log(this.select)
    },

    cascaderPick (e) {
      this.form.type_pid = e[e.length - 2] || ''
      this.form.type = e[e.length - 1] || ''
    },
    //合并行
    objectSpanMethod({ row, column, rowIndex, columnIndex }) {
      const span = column["property"] + "-span";
      if (row[span]) {
        return row[span];
      }
    },
    changeTree() {
      if (!this.isTree) {
        this.table = [
          {
            label: "隶属项目",
            prop: "pid_info_name",
            width: 200,
            align: "left",
            sortable: false,
            fixed: "left",
          },
        ].concat(this.tableItem);
      } else {
        this.table = this.tableItem;
      }
      this.getBudgets();
    },
    initLoad() {
      var that = this;
      var clientHeight = document.documentElement.clientHeight;
      var lxHeader_height = 96.5; //查询 头部
      var paginationHeight = 37; //分页的高度
      var topHeight = 50; //页面 头部
      let tableHeight =
        clientHeight - lxHeader_height - topHeight - paginationHeight - 20;
      that.tableHeight = tableHeight;
    },
    showAdd(row) {
      this.form.pid = "0";
      this.form.pid_info = null;
      this.isShowAdd = true;
      this.form.remark = "";
      this.getDepartment();
      if (row != "") {
        this.form.pid = row.id;
        this.form.pid_info = row;
      }
    },
    changeDepartments(v) {
      console.log(v);
    },
    async getTypes() {
      const res = await getparameterTree({
        id: 3
      });
      const dataHandler = (data) => {
        data.forEach(i => {
          if (i.hasOwnProperty('detail')) {
            i.children = i.detail.map(j => {
              j.name = j.value
              return j;
            })
          } else {
            dataHandler(i['children'])
          }
        })
        return data;
      }
      this.types = dataHandler(res?.children) || []
    },

    moneyRecoverEditor(key) {
      if (!/^\d{1,3}(,\d{3})*(\.\d+)/.test(this.editorForm[key])) {
        return;
      }
      this.editorForm[key] = moneyRecovery(this.editorForm[key]);
    },
    moneyFormatEditor(key) {
      if (!/^\d+(\.\d+)?$/.test(this.editorForm[key])) {
        return;
      }
      this.editorForm[key] = moneyFormatter(this.editorForm[key]);
    },
    moneyRecover(key) {
      if (!/^\d{1,3}(,\d{3})*(\.\d+)/.test(this.form[key])) {
        return;
      }
      this.form[key] = moneyRecovery(this.form[key]);
    },
    moneyFormat(key) {
      if (!/^\d+(\.\d+)?$/.test(this.form[key])) {
        return;
      }
      this.form[key] = moneyFormatter(this.form[key]);
    },
    //合计
    summary(param) {
      this.$nextTick(() => {
        if (!this.isTree) this.$refs["xyTable"].$children[0].doLayout();
        else this.$refs["treeTable"].doLayout();
      });
      const { columns, data } = param;
      const sums = [];
      columns.map((column, index) => {
        if (index === 0) {
          sums[index] = "总计";
          return;
        }
        if (column.property === "money") {
          sums[index] = moneyFormatter(this.totalMoney);
          return;
        }

        if (column.property === "update_money") {
          sums[index] = moneyFormatter(this.updateMoney);
          return;
        }
        // const values = data.map(item => Number(item[column.property]));
        // if (!values.every(value => isNaN(value)) && (column.property === 'money' || column.property === 'plan_price'|| column.property === 'fund_log_total')) {
        //
        //   sums[index] = sums[index].toFixed(2).replace(/(\d)(?=(\d{3})+\.)/g, '$1,')
        // } else {
        //   sums[index] = '';
        // }
      });
      return sums;
    },

    //翻页
    pageChange(e) {
      this.pageIndex = e;
      this.getBudgets();
    },
    pageSizeChange(e) {
      this.pageSize = e;
      this.pageIndex = 1;
      this.getBudgets();
    },
    //获取科室
    getDepartment() {
      listdeptNoAuth().then((res) => {
        this.departments = res;
      });
    },
    //查询计划列表
    getBudgets() {
      getBudget({
        name: this.select.name,
        page_size: this.pageSize,
        page: this.pageIndex,
        year: this.select.year,
        type: this.select.type,
        plan_department_id: this.select.department,
        is_tree: this.isTree ? 1 : "",
        top_pid: !this.isTree ? 1 : "",
        is_auth:this.select.is_auth,
        type_pid: this.select.type_pid,
        dimension: this.select.dimension.toString()
      }).then((res) => {
        if (this.isTree) this.treeData = res.list;
        else {
          for (var m of res.list.data) {
            m.pid_info_name = m.pid_info?.name;
          }
          this.list = mergeTableRow({
            data: res.list.data,
            mergeColNames: ["pid_info_name"], // 需要合并的列，默认合并列相同的数据
            firstMergeColNames: ["pid_info_name"], // 受影响的列，只合并以firstMerge为首的同类型数据
            firstMerge: "pid_info_name", // 以哪列为基础进行合并，一般为第一列
          });
          this.total = res.list.total;
        }
        this.totalMoney = res.total_money;
        this.updateMoney = res.update_money;
      });
    },
    //新增提交
    submit() {
      let plan_department_links = [];
      if (this.form.plan_department_link_id.length == 0) {
        Message({
          message: "请选择可用部门",
          type: "error",
        });
        return false;
      }

      this.form.plan_department_link_id.map((item) => {
        plan_department_links.push({
          department_id: item,
        });
      });

      addBudget({
        name: this.form.name,
        type: this.form.type,
        year: this.form.year,
        content: this.form.content,
        dimension: this.form.dimension,
        money: moneyRecovery(this.form.money),
        is_middle_fund: this.form.is_middle_fund,
        is_join_count: this.form.is_join_count,
        plan_department_id: this.form.department,
        plan_department_links: plan_department_links,
        remark: this.form.remark,
        pid: this.form.pid,
        type_pid: this.form.type_pid,
      }).then((res) => {
        Message({
          message: "操作成功",
          type: "success",
        });
        this.isShowAdd = false;
        this.$refs["addBudget"].reset();
        this.getBudgets();
      });
    },
    //删除
    deleteTable(e) {
      delBudget({
        id: e.id,
      }).then((res) => {
        Message({
          message: "操作成功",
          type: "success",
        });
        this.getBudgets();
      });
    },

    //修改
    editorTable() {
      this.$refs["editorDialog"].$refs["elForm"]
        .validate()
        .then((res) => {
          if (this.editorForm.plan_department_link_id.length == 0) {
            Message({
              message: "请选择可用部门",
              type: "error",
            });
            return false;
          }
          let plan_department_links = [];
          this.editorForm.plan_department_link_id.map((item) => {
            plan_department_links.push({
              department_id: item,
            });
          });
          editorBudget({
            id: this.editorForm.id,
            name: this.editorForm.name,
            type: this.editorForm.type,
            year: this.editorForm.year,
            content: this.editorForm.content,
            dimension: this.editorForm.dimension,
            money: moneyRecovery(this.editorForm.money),
            is_middle_fund: this.editorForm.is_middle_fund,
            is_join_count: this.editorForm.is_join_count,
            update_money: moneyRecovery(this.editorForm.update_money),
            remark: this.editorForm.remark,
            plan_department_id: this.editorForm.department,
            plan_department_links: plan_department_links,
            type_pid: this.editorForm.type_pid,
          }).then((res) => {
            this.isShowEditor = false;
            Message({
              message: "操作成功",
              type: "success",
            });
            this.getBudgets();
          });
        })
        .catch((err) => {
          this.$message({
            message: "请填写完整信息",
            type: "error",
          });
        });
    },
    showEditor(row) {
      this.getDepartment();
      detailBudget({
        id: row.id,
      }).then((res) => {
        this.editorForm = {
          id: res.id,
          name: res.name,
          type: res.type,
          dimension: res.dimension,
          department: res.plan_department_id,
          money: moneyFormatter(res.money),
          update_money: moneyFormatter(res.update_money),
          is_middle_fund: res.is_middle_fund,
          is_join_count: res.is_join_count,
          year: res.year,
          content: res.content,
          remark: res.remark,
          plan_department_links: res.plan_department_links,
          pid: res.pid,
          type_pid: res.type_pid,
        };
        let ids = [];
        res.plan_department_links.map((item) => {
          ids.push(item.department_id);
        });
        //this.editorForm.plan_department_link_id = ids;
        this.$set(this.editorForm, "plan_department_link_id", ids);

        this.isShowEditor = true;
        console.log(this.editorForm);
      });
    },
  },
  computed: {
    pScore () {
      return function(row) {
        return row?.plan_targets?.reduce((pre, cur) => (pre + parseFloat(cur.score||0)),0) || 0
      }
    }
  },
  created() {
    this.table = this.tableItem;
    this.initLoad();

    this.select.year = this.$moment().format("YYYY");
  },
  mounted() {
    this.getTypes();
    this.getDepartment();
    this.getBudgets();
  },
};
</script>

<style lang="scss" scoped>
.xy-table-item-label {
  width: 160px;
}

.xy-table-item-price {
  position: relative;

  &::after {
    z-index: 1;
    position: absolute;
    right: 0;
    top: 0;
    content: "（元）";
  }

  ::v-deep .el-input__clear {
    position: relative;
    right: 30px;
    z-index: 2;
  }
}

.slot-btns {
  display: flex;
  flex-wrap: wrap;
  align-content: center;
  justify-content: flex-start;

  &-item {
    margin: 0 6px 4px 0;
  }
}
</style>
