<template>
  <div>
<!--    <el-steps :active="step" align-center>-->
<!--      <el-step title="选择预算计划"> </el-step>-->
<!--      <el-step title="新增出差事项"> </el-step>-->
<!--      <el-step title="新增成功"> </el-step>-->
<!--    </el-steps>-->

    <div style="padding: 20px">
<!--      <div v-show="step === 1">-->
<!--        <div style="display: flex;justify-content: space-between;align-items: center;">-->
<!--          <DatePicker-->
<!--            :value="planSelect.year"-->
<!--            placeholder="选择所属年份"-->
<!--            placement="bottom-start"-->
<!--            style="width: 180px;margin-right: 10px;"-->
<!--            type="year"-->
<!--            @on-change="(e) => {-->
<!--              planSelect.year = e-->
<!--              getBudgets()-->
<!--            }"-->
<!--          ></DatePicker>-->
<!--          <el-select-->
<!--            placeholder="科室选择"-->
<!--            clearable-->
<!--            size="small"-->
<!--            v-model="planSelect.plan_department_id"-->
<!--            style="width: 180px;margin-right: 10px;"-->
<!--            @change="getBudgets"-->
<!--          >-->
<!--            <el-option-->
<!--              v-for="item in departments"-->
<!--              :label="item.name"-->
<!--              :value="item.id"-->
<!--              :key="item.id"-->
<!--            >-->
<!--            </el-option>-->
<!--          </el-select>-->
<!--          <el-cascader-->
<!--            placeholder="资金类型选择"-->
<!--            :options="planTypes"-->
<!--            :props="{-->
<!--                checkStrictly: false,-->
<!--                label: 'name',-->
<!--                value: 'id',-->
<!--              }"-->
<!--            :value="planSelect.type"-->
<!--            clearable-->
<!--            size="small"-->
<!--            style="width: 220px;margin-right: 10px;"-->
<!--            @change="(e) => {-->
<!--              planSelect.type = e[e.length - 1] || '';-->
<!--              getBudgets();-->
<!--            }"-->
<!--          />-->
<!--          <Input-->
<!--            v-model="planSelect.name"-->
<!--            search-->
<!--            enter-button="搜 索"-->
<!--            clearable-->
<!--            placeholder="搜索预算计划.."-->
<!--            @on-search="getBudgets"-->
<!--          />-->
<!--        </div>-->

<!--        <xy-table-->
<!--          :list="plans"-->
<!--          :show-index="false"-->
<!--          :table-item="planTable"-->
<!--          :height="boxheight"-->
<!--          style="margin-top: 10px"-->
<!--          ref="editorPlanTable"-->
<!--          row-key="id"-->
<!--          border-->
<!--          default-expand-all-->
<!--          @select="planPick"-->
<!--          :tree-props="{ children: 'notChildren', hasChildren: 'hasChildren' }"-->
<!--        >-->
<!--          <template v-slot:btns>-->
<!--            <el-table-column-->
<!--              label="使用金额（元）"-->
<!--              header-align="center"-->
<!--              width="144"-->
<!--            >-->
<!--              <template slot-scope="scope" v-if="scope.row.pid === 0">-->
<!--                <InputNumber-->
<!--                  style="width: 120px"-->
<!--                  :min="0"-->
<!--                  :precision="2"-->
<!--                  :active-change="false"-->
<!--                  v-model="scope.row._inputMoney"-->
<!--                  :formatter="-->
<!--                    (value) => `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ',')-->
<!--                  "-->
<!--                  :parser="(value) => value.replace(/\$\s?|(,*)/g, '')"-->
<!--                ></InputNumber>-->
<!--              </template>-->
<!--            </el-table-column>-->
<!--          </template>-->
<!--        </xy-table>-->
<!--        <div style="display: flex; justify-content: flex-end">-->
<!--          <Page-->
<!--            :total="planTotal"-->
<!--            show-elevator-->
<!--            @on-change="-->
<!--              (e) => {-->
<!--                planSelect.page = e;-->
<!--                getBudgets();-->
<!--              }-->
<!--            "-->
<!--          />-->
<!--        </div>-->
<!--        <div style="text-align: center">-->
<!--          <el-button type="primary" style="margin-top: 12px" @click="() => nextStep()"-->
<!--          >下一步</el-button-->
<!--          >-->
<!--        </div>-->
<!--      </div>-->


      <el-card v-show="step === 2">
<!--        <el-popover placement="right-start" width="660" trigger="click">-->
<!--          <xy-table-->
<!--            :list="planSelections"-->
<!--            size="mini"-->
<!--            :table-item="[-->
<!--              ...planTable.slice(1),-->
<!--              {-->
<!--                width: 120,-->
<!--                align: 'right',-->
<!--                label: '使用金额（元）',-->
<!--                prop: '_inputMoney',-->
<!--                formatter: (v1, v2, value) =>-->
<!--                  `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ','),-->
<!--              },-->
<!--            ]"-->
<!--            :height="400"-->
<!--            style="width: 100%"-->
<!--            row-key="id"-->
<!--            border-->
<!--            :tree-props="{-->
<!--              children: 'notChildren',-->
<!--              hasChildren: 'hasChildren',-->
<!--            }"-->
<!--          >-->
<!--            <template #btns></template>-->
<!--          </xy-table>-->
<!--          <el-button-->
<!--            icon="el-icon-s-order"-->
<!--            size="small"-->
<!--            type="primary"-->
<!--            slot="reference"-->
<!--          >查看已选预算计划（{{ planSelections.length }}）</el-button-->
<!--          >-->
<!--        </el-popover>-->

        <el-form :model="form" :rules="rules" ref="form" label-width="120px" style="margin-top: 20px;">
          <el-form-item label="出差事由" prop="title">
            <el-input clearable placeholder="请输入标题" v-model="form.title" style="max-width: 300px;width: 100%;"></el-input>
          </el-form-item>
          <!--        <el-form-item label="是否用车" prop="use_car">-->
          <!--          <el-radio-group v-model="form.use_car">-->
          <!--            <el-radio :label="1">是</el-radio>-->
          <!--            <el-radio :label="0">否</el-radio>-->
          <!--          </el-radio-group>-->
          <!--        </el-form-item>-->
          <el-form-item label="开始时间" prop="start_date">
            <el-date-picker value-format="yyyy-MM-dd" clearable placeholder="请选择开始时间" style="max-width: 300px;width: 100%;" v-model="form.start_date"></el-date-picker>
          </el-form-item>
          <el-form-item label="结束时间" prop="end_date">
            <el-date-picker value-format="yyyy-MM-dd"
                            clearable
                            placeholder="请选择结束时间"
                            style="max-width: 300px;width: 100%;"
                            v-model="form.end_date"></el-date-picker>
          </el-form-item>
          <!--        <el-form-item label="是否室内补助" prop="is_subsidize">-->
          <!--          <el-radio-group v-model="form.is_subsidize">-->
          <!--            <el-radio :label="1">是</el-radio>-->
          <!--            <el-radio :label="0">否</el-radio>-->
          <!--          </el-radio-group>-->
          <!--        </el-form-item>-->
          <div style="display: flex;justify-content: center;">
<!--            <el-button type="primary" plain @click="forwardStep">上一步</el-button>-->
            <el-button type="warning" plain @click="reset">重置</el-button>
            <el-button :loading="loading" type="primary" @click="submit">提交</el-button>
          </div>
        </el-form>
      </el-card>
    </div>


  </div>
</template>

<script>
import { deepCopy } from "@/utils";
import { save, show } from "@/api/away"
import {getBudget} from "@/api/budget/budget";
import {listdeptNoAuth} from "@/api/system/department";
import {getparameterTree} from "@/api/system/dictionary";
export default {
  data() {
    return {
      planTypes: [],
      departments: [],

      id: "",
      step: 2,
      loading: false,
      plans: [],
      boxheight: 300,
      planSelect: {
        name: "",
        page_size: 20,
        page: 1,
        is_tree: 1,
        year: new Date().getFullYear().toString(),
        plan_department_id: "",
        type: ""
      },
      planTable: [
        {
          sortable: false,
          width: 44,
          type: "selection",
          reserveSelection: true,
          fixed: "left",
          selectable: (row, index) => {
            return row.pid === 0;
          },
        },
        {
          label: "科室",
          prop: "plan_department.name",
          width: 120,
          align: "center",
        },
        {
          label: "年份",
          prop: "year",
          width: 80,
          align: "center",
        },
        {
          label: "分类",
          prop: "type_detail.value",
          width: 120,
        },
        {
          label: "名称",
          prop: "name",
          minWidth: 180,
          align: "left",
        },
        {
          label: "内容",
          prop: "content",
          minWidth: 200,
          align: "left",
        },
        {
          label: "计划金额",
          prop: "money",
          align: "right",
          width: 120,
          formatter: (v1, v2, value) => {
            return `${(value && parseFloat(value) !== 0) ? value : v1.update_money }`.replace(/\B(?=(\d{3})+(?!\d))/g, ",")
          }
        },
        {
          label: "实付金额",
          prop: "use_money_total",
          width: 120,
          align: "right",
          formatter: (v1, v2, value) =>
            value ? `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ",") : "",
        },
        {
          label: "已用金额",
          prop: "has_money_total",
          width: 120,
          align: "right",
          formatter: (v1, v2, value) =>
            value ? `${value}`.replace(/\B(?=(\d{3})+(?!\d))/g, ",") : "",
        },
      ],
      planTotal: 0,


      form: {
        title: '',
        //use_car: 0,
        start_date: '',
        end_date: '',
        //is_subsidize: 0,
        // use_car_status: 1,
        // subsidize_status: 1,
        expense_status: 1,
        away_status: 1,
        away_plan_links: []
      },
      copyForm: {

      },
      rules: {
        title: [
          { required: true, message: '请输入标题', trigger: 'blur' },
        ],
        start_date: [
          { required: true, message: '请选择开始时间', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (this.form.end_date && this.form.start_date) {
                if (this.$moment(this.form.end_date).isAfter(this.form.start_date) || (this.form.end_date === this.form.start_date)) {
                  callback()
                } else {
                  callback(new Error('结束时间不能小于开始时间'))
                }
              } else {
                callback()
              }
            }
          }
        ],
        end_date: [
          { required: true, message: '请选择结束时间', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (this.form.end_date && this.form.start_date) {
                if (this.$moment(this.form.end_date).isAfter(this.form.start_date) || (this.form.end_date === this.form.start_date)) {
                  callback()
                } else {
                  callback(new Error('结束时间不能小于开始时间'))
                }
              } else {
                callback()
              }
            }
          }
        ],
      }
    }
  },
  methods: {
    forwardStep () {
      this.step = this.step > 1 ? this.step - 1 : this.step;
    },
    nextStep () {
      if (this.step === 1) {
        const selections = this.$refs["editorPlanTable"].getSelection();
        if (selections?.length > 0) {
          for (let i of selections) {
            if (i._inputMoney <= 0) {
              this.$message({
                type: "warning",
                message: `【${i.year}】${i.name} 使用金额需要大于0！`,
              });
              return;
            }
            if (i._inputMoney > ((Number(i.money) || Number(i.update_money)) - Number(i.has_money_total))) {
              this.$message({
                type: "warning",
                message: `【${i.year}】${i.name} 使用金额大于剩余预算！`,
              });
              return;
            }
          }
          this.form.away_plan_links = selections.map((i) => ({
            plan_id: i.id,
            use_money: i._inputMoney,
            new_money: i.money,
          }));
          this.step = 2;
        } else {
          this.$message({
            type: "warning",
            message: "请先选择预算计划！",
          });
        }
      }
    },

    planPick (selection, row) {
      if (row.year != new Date().getFullYear()) {
        this.$confirm("您选择了非本年预算，是否继续？").catch(_ => {
          this.$refs['editorPlanTable'].toggleRowSelection(row)
        })
      }
    },
    //获取预算计划
    async getBudgets() {
      let res = await getBudget(this.planSelect);
      res.list.forEach((item) => (item._inputMoney = 0));
      this.plans = res.list;
      this.planTotal = res.list.total || 0;
    },
    getDepartment() {
      listdeptNoAuth().then((res) => {
        this.departments = res;
      });
    },
    async getPlanTypes() {
      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.planTypes = dataHandler(res?.children) || []
    },

    init () {
      this.copyForm = deepCopy(this.form)
      this.getBudgets()
      this.getDepartment()
      this.getPlanTypes()
      this.boxheight = document.documentElement.clientHeight - 400;
    },

    reset () {
      this.$set(this, "form", this.copyForm)
      //this.form = deepCopy(this.copyForm)
      this.$refs["editorPlanTable"].clearSelection()
      this.$nextTick(() => this.$refs.form.clearValidate())
    },

    submit () {
      this.loading = true
      this.$refs.form.validate((valid) => {
        if (valid) {
          // this.form.use_car_status = this.form.use_car ? 1 : "";
          // this.form.subsidize_status = this.form.is_subsidize ? 1 : "";
          save(this.form,true).then(res => {
            this.loading = false
            this.$message({
              message: '提交成功',
              type:'success'
            })
            setTimeout(() => {
              this.$router.push("/contract/away")
            },500)
          }).catch(err => {
            this.loading = false
          })
        } else {
          return false
        }
      })
    }
  },
  computed: {
    planSelections() {
      let temp = this.form.away_plan_links;
      return this.$refs["editorPlanTable"]?.getSelection() || [];
    },
  },
  created() {
    this.init();
  }
}
</script>

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