<template>
  <div>
    <xy-dialog
      ref="dialog"
      :is-show.sync="isShow"
      type="form"
      title="付款计划"
      :form="form"
      @reset="getDetail"
      @submit="submit"
    >
      <template v-slot:plan_id>
        <div class="xy-table-item">
          <div class="xy-table-item-label">项目 ：</div>
          <div class="xy-table-item-content">
            <el-input
              readonly
              :value="rowName"
              clearable
              placeholder="请输入项目"
              style="width: 300px"
            ></el-input>
          </div>
        </div>
      </template>

      <template #item_list>
        <el-button
          icon="el-icon-plus"
          type="primary"
          size="small"
          @click="
            formList.push({
              plan_id: id,
              paid_money: 0,
              remark: '',
              paid_plan_date: '',
            })
          "
          >新增</el-button
        >
        <xy-table
          style="margin-top: 20px"
          :height="320"
          :table-item="itemTable"
          :list="formList"
        >
          <template #btns> </template>
        </xy-table>
      </template>
    </xy-dialog>
  </div>
</template>

<script>
import { paidSave, paidIndex, paidStore, paidDestroy } from "@/api/budget/paidPlan"
export default {
  props: {},
  data() {
    return {
      isShow: false,
      id: "",
      type: "",
      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < new Date(new Date().getFullYear(), new Date().getMonth(), 1).getTime();
        }
      },
      itemTable: [
        {
          prop: "paid_money",
          label: "付款金额",
          width: 180,
          sortable: false,
          customFn: (row) => {
            return (
              <el-input-number
                precision={2}
                controls={false}
                placeholder="付款金额"
                style="width: 100%;"
                v-model={row.paid_money}
                size="small"
                clearable={true}

                on={{
                  ['change']:e => {
                    if (row.id) {
                      this.editId.push(row.id)
                    }
                  }
                }}
              ></el-input-number>
            );
          },
        },
        {
          prop: "paid_plan_date",
          label: "年份-月份",
          sortable: false,
          width: 140,
          customFn: (row) => {
            return (
              <el-date-picker
                type="month"
                placeholder="年份-月份"
                style="width: 100%;"
                value-format="yyyy-MM"
                v-model={row.paid_plan_date}
                size="mini"
                clearable={true}
                pickerOptions={this.pickerOptions}
                on={{
                  ['change']:e => {
                    if (row.id) {
                      this.editId.push(row.id)
                    }
                  }
                }}
              ></el-date-picker>
            );
          },
        },
        {
          prop: "remark",
          label: "备注",
          sortable: false,
          minWidth: 200,
          customFn: (row) => {
            return (
              <el-input
                v-model={row.remark}
                placeholder="备注"
                style="width: 100%;"
                size="mini"
                clearable={true}
                on={{
                  ['change']:e => {
                    if (row.id) {
                      this.editId.push(row.id)
                    }
                  }
                }}
              ></el-input>
            );
          },
        },
        {
          label: "操作",
          width: 180,
          align: "left",
          sortable: false,
          customFn: (row, scope) => {
            return (
              <Poptip
                confirm={true}
                transfer={true}
                placement="bottom"
                title="确认要删除吗"
                on={{
                  ["on-ok"]: (_) => {
                    if (!row.id) {
                      this.formList.splice(scope.$index, 1);
                    } else {
                      paidDestroy({
                        id: row.id
                      }).then(res => {
                        this.$message({
                          type: 'success',
                          message: '删除成功'
                        })
                        this.getDetail();
                      })
                    }
                  },
                }}
              >
                <Button
                  style="margin-left: 4px;"
                  ghost
                  size="small"
                  type="error"
                >
                  删除
                </Button>
              </Poptip>
            );
          },
        },
      ],
      rowName: "",
      formList: [],
      editId: [],
      form: {
        plan_id: "",
        item_list: [],
      },
    };
  },
  methods: {
    show() {
      this.isShow = true;
    },
    hidden() {
      this.isShow = false;
    },
    init() {
      for (let key in this.form) {
        if (this.form[key] instanceof Array) {
          this.form[key] = [];
        } else {
          this.form[key] = "";
        }
      }
      this.$refs["dialog"].clearValidate();
    },
    setId(id) {
      if (typeof id == "number") {
        this.id = id;
      } else {
        console.error("error typeof id: " + typeof id);
      }
    },
    getId() {
      return this.id;
    },
    setType(type = "add") {
      let types = ["add", "editor"];
      if (types.includes(type)) {
        this.type = type;
      } else {
        console.warn("Unknown type: " + type);
      }
    },
    setForm(key = [], value = []) {
      if (key instanceof Array) {
        key.forEach((key, index) => {
          this.form[key] = value[index] ?? "";
        });
      }
      if (typeof key === "string") {
        this.form[key] = value;
      }
      if (!key) {
        this.init();
      }
    },

    async getDetail() {
      let res = await paidIndex({
        plan_id: this.id
      })
      this.formList = res.data;
    },

    submit() {
      for(let i = 0;i < this.formList.length;i++) {
        if (!this.formList[i]?.paid_plan_date || !this.formList[i]?.paid_money) {
          this.$message({
            type: 'warning',
            message: `第${i+1}条金额或日期未填写`
          })
          return
        }
      }
      let editIds = Array.from(new Set(this.editId))
      let promiseAll = [];
      editIds.forEach(id => {
        promiseAll.push(paidSave(this.formList.find(i => i.id === id)))
      })
      for (let i = 0;i < this.formList.length;i++) {
        if (!this.formList[i].id) {
          promiseAll.push(paidStore(this.formList[i]))
        }
      }

      if (promiseAll.length > 0) {
        Promise.all(promiseAll).then(res => {
          this.$message({
            type: 'success',
            message: '保存成功'
          })
          this.hidden();
        })
      }
    },
  },
  watch: {
    isShow(val) {
      if (val) {
        this.getDetail();
      } else {
        this.id = "";
        this.type = "";
        this.rowName = "";
        this.init();
        this.formList = [];
        this.editId = [];
        this.$refs["dialog"].clearValidate();
        delete this.form.id;
      }
    },
  },
  created() {},
};
</script>

<style scoped lang="scss">
::v-deep .el-input__inner {
  text-align: left;
}
.xy-table-item-label {
  width: 150px;
}

.select {
  margin-bottom: 10px;

  & > * {
    margin-left: 6px;
  }
}
</style>
