<template>
  <view class="incomeSort">
    <view>
      <uni-forms ref="form" :rules="rules" :model="form" class="form" label-position="top" label-width="100%"
        validate-trigger="bind">
        <uni-forms-item label="一级分类" name="firstId">
          <uni-data-select v-model="form.firstId" :localdata="firstList" placeholder="请选择一级分类" @change="handleChange" />
        </uni-forms-item>
        <uni-forms-item label="二级分类" name="secondId">
          <uni-data-select v-model="form.secondId" :localdata="secondList" placeholder="请选择二级分类" />
        </uni-forms-item>
        <uni-forms-item label="记账时间" name="billingTime">
          <uni-datetime-picker type="date" v-model="form.billingTime" placeholder="请选择记账时间" />
        </uni-forms-item>
        <uni-forms-item label="金额(元)" name="amount">
          <uni-easyinput v-model="form.amount" placeholder="请输入金额(元)" type="number" />
        </uni-forms-item>
        <uni-forms-item label="贷款时间" name="loanDate" v-if="this.loansState">
          <uni-datetime-picker type="date" v-model="form.loanDate" placeholder="请选择贷款时间" />
        </uni-forms-item>
        <uni-forms-item label="贷款银行" name="bank" v-if="this.loansState">
          <uni-easyinput v-model="form.bank" placeholder="请输入贷款银行" />
        </uni-forms-item>
        <uni-forms-item label="贷款用途" name="loanUse" v-if="this.loansState">
          <uni-data-select v-model="form.loanUse" placeholder="请选择贷款用途" :localdata="dictLists['loan_use']" />
        </uni-forms-item>
        <uni-forms-item label="贷款期限" prop="loanLimit" v-if="this.loansState">
          <uni-easyinput v-model="form.loanLimit" placeholder="请输入贷款期限" />
        </uni-forms-item>
        <uni-forms-item label="贷款月息" prop="loanInterest" v-if="this.loansState">
          <uni-easyinput v-model="form.loanInterest" placeholder="请输入贷款月息" />
        </uni-forms-item>
        <uni-forms-item label="借款来源" prop="borrowOrigin" v-if="this.borrowState">
          <uni-data-select v-model="form.borrowOrigin" placeholder="请选择贷款用途" :localdata="dictLists['loan_orgin']" />
        </uni-forms-item>
        <uni-forms-item label="借款时间" prop="borrowDate" v-if="this.borrowState">
          <uni-datetime-picker type="date" v-model="form.borrowDate" placeholder="请选择借款时间" />
        </uni-forms-item>
        <uni-forms-item label="借款用途" prop="borrowUse" v-if="this.borrowState">
          <uni-data-select v-model="form.borrowUse" placeholder="请选择贷款用途" :localdata="dictLists['loan_use']" />
        </uni-forms-item>
        <uni-forms-item label="借款时长" prop="borrowLimit" v-if="this.borrowState">
          <uni-easyinput v-model="form.borrowLimit" placeholder="请输入借款时长" />
        </uni-forms-item>
        <uni-forms-item label="借款月息" prop="borrowInterest" v-if="this.borrowState">
          <uni-easyinput v-model="form.borrowInterest" placeholder="请输入借款月息" />
        </uni-forms-item>
        <uni-forms-item label="还款来源" prop="repaymentOrigin" v-if="this.borrowState">
          <uni-data-select v-model="form.repaymentOrigin" placeholder="请选择还款来源" :localdata="dictLists['loan_orgin']" />
        </uni-forms-item>
        <uni-forms-item label="保险公司" prop="insuranceCompany" v-if="this.insuranceState">
          <uni-data-select v-model="form.insuranceCompany" placeholder="请选择保险公司"
            :localdata="dictLists['insurance_compan']" />
        </uni-forms-item>
        <uni-forms-item label="保险品种" prop="insuranceItem" v-if="this.insuranceState">
          <uni-easyinput v-model="form.insuranceItem" placeholder="请输入保险品种" />
        </uni-forms-item>
        <uni-forms-item label="灾害原因" prop="disaster" v-if="this.insuranceState">
          <uni-data-select v-model="form.disaster" placeholder="请选择灾害原因" :localdata="dictLists['disaster']" />
        </uni-forms-item>
        <uni-forms-item label="其他收入" prop="otherIncome" v-if="this.elseState">
          <uni-easyinput v-model="form.otherIncome" placeholder="请输入其他收入" />
        </uni-forms-item>
      </uni-forms>
    </view>
    <view style="height: 44px">
      <button v-if="false">
        <text>{{ "测 试" }}</text>
      </button>
    </view>

    <view v-if="true" class="foot">
      <button @click="cencel" :plain="false" class="cencel">
        <text>{{ "取 消" }}</text>
      </button>
      <button @click="showConfirm" type="primary" class="confirm">
        <text>{{ "确 认" }}</text>
      </button>
    </view>
  </view>
</template>

<script>
import {
  listIncome,
  getIncome,
  delIncome,
  addIncome,
  updateIncome,
} from "@/api/income/income";
import {
  queryIncomeCategory,
  queryIncomeByPid,
  getIncomeCategory,
  listIncomeCategory,
} from "@/api/income/incomeCategory";
export default {
  name: "incomeSort",
  components: {},
  props: {},
  data() {
    return {
      contractUrl: [],
      options: {},
      form: {},
      dictLists: {},
      list: [],
      firstList: [],
      secondList: [],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      rules: {
        firstId: {
          rules: [
            {
              required: true,
              errorMessage: "请选择分类",
            },
          ],
        },
        billingTime: {
          rules: [
            {
              required: true,
              errorMessage: "请输入记账时间",
            },
          ],
        },
        amount: {
          rules: [
            {
              required: true,
              errorMessage: "请输入金额",
            },
          ],
        },
      },
      incomeCategoryList: [],
      incCaDetailList: [],
      //贷款
      loansState: false,
      //借款
      borrowState: false,
      //保险
      insuranceState: false,
      //其他
      elseState: true,
    };
  },
  computed: {},
  methods: {
    // 表单重置
    reset() {
      this.form = {
        id: null,
        baseId: null,
        firstId: null,
        secondId: null,
        billingTime: null,
        amount: null,
        area: null,
        repayment: null,
        repaymentDate: null,
        borrow: null,
        insurance: null,
        createBy: null,
        createTime: null,
        updateBy: null,
        updateTime: null,
      };
    },
    async getRouter(options) {
      this.options = options;
    },
    naviBack(isNew) {
      let pages = getCurrentPages(); //关于获取页面的官方文档https://uniapp.dcloud.io/api/window/window
      let prevPage = pages[pages.length - 2];
      uni.navigateBack({
        delta: 1,
        success: () => {
          if (isNew !== undefined) {
            setTimeout(function () {
              prevPage.$vm.getMsg(isNew);
            }, 200);
          }
        },
      });
    },
    cencel() {
      this.naviBack();
    },
    submitForm() {
      let form = this.form;
      let isNew = form.id === null || form.id === undefined || form.id === "";
      form.secondId =
        form.secondId === null || form.secondId === ""
          ? form.firstId
          : form.secondId;
      form.firstId = null;
      if (isNew) {
        addIncome(form).then((response) => {
          this.naviBack(isNew);
        });
      } else {
        updateIncome(form).then((response) => {
          this.naviBack(isNew);
        });
      }
    },
    //获取到选中支出分类ID
    handleChange(value) {
      const that = this;
      this.secondList = [];
      this.form.secondId =
        that.form.firstId === value ? this.form.secondId : null;
      if (typeof value === "undefined" || value == null || value === "") {
      } else {
        that.incomeCategoryList.forEach((element) => {
          if (element.value === value) {
            element.children.forEach((CEle) => {
              this.secondList.push({ value: CEle.value, text: CEle.label });
            });
          }
          this.decideShowBySelId(value);
        });
      }
    },
    /** 查询支出分类列表 */
    getincomeSortCategoryList() {
      queryIncomeCategory().then((response) => {
        this.incomeCategoryList = response.data;
        response.data.forEach((val, index) => {
          this.firstList.push({ value: val.value, text: val.label });
        });
      });
    },
    getLists() {
      listIncomeCategory({ status: 0 }).then((res) => {
        res.data.forEach((element) => {
          this.$set(this.incCaDetailList, [element.id], element);
        });
      });
    },
    //获取到选中支出分类ID
    decideShowBySelId(value) {
      const that = this;
      var loans = /贷款/;
      var borrow = /借款/;
      var insurance = /保险/;
      if (loans.test(that.incCaDetailList[value].name)) {
        this.loansState = true;
        this.borrowState = false;
        this.insuranceState = false;
        this.elseState = false;
      } else if (borrow.test(that.incCaDetailList[value].name)) {
        this.loansState = false;
        this.borrowState = true;
        this.insuranceState = false;
        this.elseState = false;
      } else if (insurance.test(that.incCaDetailList[value].name)) {
        this.loansState = false;
        this.borrowState = false;
        this.insuranceState = true;
        this.elseState = false;
      } else {
        this.loansState = false;
        this.borrowState = false;
        this.insuranceState = false;
        this.elseState = true;
      }
    },
    async initializeDict() {
      this.dictByType("loan_use");
      this.dictByType("disaster");
      this.dictByType("insurance_compan");
      this.dictByType("loan_orgin");
    },
    dictByType(type) {
      this.getDicts(type).then((response) => {
        let dicts = [];
        for (let dict of response.data) {
          let element = {};
          element["value"] = dict.dictValue;
          element["text"] = dict.dictLabel;
          element["label"] = dict.dictLabel;
          dicts.push(element);
        }
        this.$set(this.dictLists, type, dicts);
      });
    },
    showConfirm() {
      this.$refs["form"].validate().then((res) => {
        this.$modal.confirm("确认提交").then((res) => {
          if (res === true) {
            this.submitForm();
          }
        });
      });
    },
  },
  watch: {
    loading: {
      handler: function (val, oldVal) {
        if (val === true) {
          this.$modal.loading("加载中，请耐心等待...");
        } else {
          this.$modal.closeLoading();
        }
      },
      deep: true,
    },
  },

  // 页面周期函数--监听页面加载
  onLoad(options) {
    this.initializeDict();
    this.reset();
    this.getRouter(options).then(() => {
      if (options.id != undefined) {
        this.getLandManagementById();
      }
    });
    this.getincomeSortCategoryList();
    this.getLists();
  },
  // 页面周期函数--监听页面初次渲染完成
  onReady() { },
  // 页面周期函数--监听页面显示(not-nvue)
  onShow() { },
  // 页面周期函数--监听页面隐藏
  onHide() { },
  // 页面周期函数--监听页面卸载
  onUnload() {
    const that = this
    return that.$listenOB.goBack()
  },
  // 页面处理函数--监听用户下拉动作
  // onPullDownRefresh() { uni.stopPullDownRefresh(); },
  // 页面处理函数--监听用户上拉触底
  // onReachBottom() {},
  // 页面处理函数--监听页面滚动(not-nvue)
  // onPageScroll(event) {},
  // 页面处理函数--用户点击右上角分享
  // onShareAppMessage(options) {},
};
</script>

<style lang="scss" scoped>
page {
  background: white;
}

.incomeSort {
  background-color: white;
  height: calc(100%);

  .foot {
    width: 100vw;
    height: 44px;
    bottom: 0px;
    display: flex;
    position: fixed;
    z-index: 2;

    .cencel {
      border-radius: 0px;
      border: 0px;
      width: 50%;
      background-color: white;
    }

    .confirm {
      border-radius: 0px;
      border: 0px;
      width: 50%;
      color: white;
    }
  }
}

.form {
  text-align: center;
  margin: auto;
  width: 80%;

  /deep/ .flex-radio {
    uni-radio-group {
      width: 100%;

      .checklist-group {
        display: flex;
        justify-content: space-evenly;
      }
    }
  }

  /deep/ .uni-forms-item {
    .uni-forms-item__content {
      .uni-file-picker {
        .uni-file-picker__header {
          .file-title {
            span {
              color: #ff0000a6;
            }
          }
        }
      }

      .uni-mt-5 {
        .uni-icons {
          background: #007aff21;
          line-height: 35px;
          height: 35px;
        }
      }

      .uni-select-cy {
        z-index: 1;

        .uni-select-cy-select {
          z-index: -500;
        }
      }
    }
  }
}
</style>
