<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="借贷部门" prop="queryDebitDeptId">
        <treeselect
          v-model="queryParams.queryDebitDeptId"
          :options="queryDeptOptions"
          :show-count="true"
          placeholder="请输入借贷部门"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="出借部门" prop="queryLendDeptId">
        <treeselect
          v-model="queryParams.queryLendDeptId"
          :options="queryDeptOptions"
          :show-count="true"
          placeholder="请输入出借部门"
          style="width: 200px"
        />
      </el-form-item>
      <el-form-item label="登记日期" prop="registerTime">
        <el-date-picker clearable size="small"
          v-model="queryParams.registerTime"
          type="datetime"
          value-format="yyyy-MM-dd HH:mm:ss"
          placeholder="选择登记日期">
        </el-date-picker>
      </el-form-item>
      <!--<el-form-item label="使用人" prop="useId">
        <el-select v-model="queryParams.useId" placeholder="请选择使用人">
          <el-option v-for="item in usersList"
                     :key="item.userId"
                     :label="item.nickName"
                     :value="item.userId"/>
        </el-select>
      </el-form-item>-->
      <el-form-item label="借贷状态" prop="debitStatus">
        <el-select v-model="queryParams.debitStatus" placeholder="请选择借贷状态" clearable size="small">
          <el-option
            v-for="item in debitStatusList"
            :key="item.dictValue"
            :label="item.dictLabel"
            :value="item.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

  <!--  <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['system:credit:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['system:credit:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['system:credit:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="el-icon-download"
          size="mini"
		  :loading="exportLoading"
          @click="handleExport"
          v-hasPermi="['system:credit:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>-->

    <!--部长查询借贷列表-->
    <el-card class="box-card" v-if="$store.state.user.roles.findIndex(item =>item == 'deptLeader') != -1">
      <div class="outer-div">
        <header class="header">
          <ul class="tab-tilte">
            <li :class="{ active: tab == 0 }" @click="changeTab(0)">
              所有项目
            </li>
            <li :class="{ active: tab == 1 }" @click="changeTab(1)">
              我申请的
            </li>
            <li :class="{ active: tab == 2 }" @click="changeTab(2)">
              我审批的
            </li>
          </ul>
          <el-button
            @click="handleAdd"
            v-hasPermi="['system:credit:add']"
            class="applyDebit"
          >申请借贷</el-button
          >
        </header>

        <div class="tab-content">
          <!-- 可以使用自定义组件 -->
          <!-- <component-one v-show="tab == 0"></component-one>
          <component-two v-show="tab == 1"></component-two> -->
          <div v-if="tab == 0" :key="tab">
            <TableList
              :queryParams="queryParams"
              :creditList="creditList"
              :total="total"
              :loading="loading"
              @getList="getList"
            />
          </div>
          <div v-if="tab == 1" :key="tab">
            <TableList
              :queryParams="queryParams"
              :creditList="creditList"
              :total="total"
              :loading="loading"
              @getList="getList"
            />
          </div>
          <div v-if="tab == 2" :key="tab">
            <TableList
              :queryParams="queryParams"
              :creditList="creditList"
              :total="total"
              :loading="loading"
              @getList="getList"
            />
          </div>
        </div>
      </div>
    </el-card>

    <!--核算部及其他角色-->
    <el-card class="box-card" v-else>
      <TableList
        :queryParams="queryParams"
        :creditList="creditList"
        :total="total"
        :loading="loading"
        @getList="getList"
      />
    </el-card>

    <!-- 添加或修改借贷对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body :close-on-click-modal="false" destroy-on-close>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="出借部门" prop="lendDeptId">
              <treeselect
                v-model="form.lendDeptId"
                :options="formDeptOptions"
                :show-count="true"
                placeholder="请输入出借部门"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="使用人" prop="useId">
              <el-select v-model="form.useId" placeholder="请选择使用人" style="width: 100%">
                <el-option v-for="item in usersList"
                           :key="item.userId"
                           :label="item.nickName"
                           :value="item.userId"/>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="使用说明" prop="useDescribe">
          <el-input v-model="form.useDescribe" type="textarea" placeholder="请输入内容" />
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="小写合计" prop="littleTotal">
              <el-input-number v-model="form.littleTotal" :precision="2" @blur="getCapitalTotal" style="width: 100%"/>
              <!--<el-input v-model="form.littleTotal" placeholder="请输入小写合计(精确到分)" @blur="getCapitalTotal"
                        oninput="value=value.replace(/^\D*([0-9]+\.[0-9]{0,2}).*$/,'$1')"/>-->
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="大写合计" prop="capitalTotal">
              <el-input v-model="form.capitalTotal" placeholder="请输入大写合计" disabled/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="计息日" prop="sumInterestDate">
              <el-date-picker clearable size="small"
                              v-model="form.sumInterestDate"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="选择计息日"
                              style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="预计还款日" prop="expectedRepaymentDate">
              <el-date-picker clearable size="small"
                              v-model="form.expectedRepaymentDate"
                              type="datetime"
                              value-format="yyyy-MM-dd HH:mm:ss"
                              placeholder="选择预计还款日"
                              style="width: 100%">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="附件" prop="attachmentUrl">
          <FileUpload
            listType="picture"
            @resFun="getFileInfo"
            @remove="listRemove"
            :fileArr="fileList"
            :fileSize="500"
            :fileType="['png','jpg','jpeg','mp4','doc','xls','ppt','txt','pdf',]"/>
          <el-input v-show="false" disabled v-model="form.attachmentUrl"></el-input>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" placeholder="请输入备注" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer" style="text-align: center">
        <el-button style="width: 150px; border-color: #1890ff; color: #1890ff" @click="reset">内容重置</el-button>
        <el-button type="primary" style="width: 150px" @click="submitForm">提交申请</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { listCredit, getCredit, delCredit, addCredit, updateCredit, exportCredit, selectDebitListByRoles } from "@/api/debit/credit";
import FileUpload from "@/components/FileUpload";
import uploadfile from "@/assets/uploadfile.png";
import { selectTransactorByDeptId } from "@/api/system/user";
import { treeselect } from "@/api/system/dept";
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import TableList from "./components/TableList";
export default {
  name: "Credit",
  components: {
    Treeselect,
    FileUpload,
    TableList
  },
  data() {
    let validateExpectedRepaymentDate = (rule, value, callback) => {
      if (this.form.expectedRepaymentDate > this.form.sumInterestDate) {
        callback()
      } else {
        callback(
          new Error("预计还款日期不能小于计息日！")
        )
      }
    }
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 借贷表格数据
      creditList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        debitDeptId: null,
        operatorId: null,
        lendDeptId: null,
        registerTime: null,
        useDescribe: null,
        useId: null,
        capitalTotal: null,
        littleTotal: null,
        dayRate: null,
        sumInterestDate: null,
        expectedRepaymentDate: null,
        approvalId: null,
        debitStatus: null,
        attachmentUrl: null,
        realPaymentDate: null,
        realPaymentAcount: null,
        isDel: null,
        queryType: "all",
        queryDebitDeptId: null,
        queryLendDeptId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        lendDeptId: [
          { required: true, message: "请选择出借部门", trigger: "change" },
        ],
        operatorId: [
          { required: true, message: "请选择使用人", trigger: "change" },
        ],
        useDescribe: [
          { required: true, message: "请输入使用说明", trigger: "blur" },
        ],
        littleTotal: [
          { required: true, message: "请输入小写合计", trigger: "blur" },
        ],
        sumInterestDate: [
          { required: true, message: "请选择计息日期", trigger: "change" },
        ],
        expectedRepaymentDate: [
          { required: true, message: "请选择预计还款日期", trigger: "change" },
          { validator: validateExpectedRepaymentDate, trigger: 'change' }
        ],
      },
      fileList: [],
      usersList: [],
      formDeptOptions: [],
      tab: "0",
      debitStatusList: [],
      queryDeptOptions: []
    };
  },
  created() {
    this.getList();
    //获取使用人
    this.getUsers();
    //获取部门
    this.getTreeselect();
    this.getDicts("t_debit_status").then((response) => {
      this.debitStatusList = response.data;
    });
  },
  methods: {
    /** 查询借贷列表 */
    getList() {
      this.loading = true;
      selectDebitListByRoles(this.queryParams).then(response => {
        this.creditList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        debitId: null,
        debitDeptId: null,
        operatorId: null,
        lendDeptId: null,
        registerTime: null,
        useDescribe: null,
        useId: null,
        capitalTotal: null,
        littleTotal: null,
        dayRate: null,
        sumInterestDate: null,
        expectedRepaymentDate: null,
        approvalId: null,
        debitStatus: "0",
        attachmentUrl: null,
        realPaymentDate: null,
        realPaymentAcount: null,
        createTime: null,
        updateTime: null,
        isDel: null,
        remark: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.debitId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加借贷";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const debitId = row.debitId || this.ids
      getCredit(debitId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改借贷";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.debitId != null) {
            updateCredit(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            this.form.debitDeptId = this.$store.state.user.deptId;
            this.form.operatorId = this.$store.state.user.userId;
            this.form.dayRate = 0.08/360;
            addCredit(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const debitIds = row.debitId || this.ids;
      this.$confirm('是否确认删除借贷编号为"' + debitIds + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(function() {
          return delCredit(debitIds);
        }).then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有借贷数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.exportLoading = true;
          return exportCredit(queryParams);
        }).then(response => {
          this.download(response.msg);
          this.exportLoading = false;
        }).catch(() => {});
    },
    getCapitalTotal(){
      this.form.capitalTotal = this.smallToBig(this.form.littleTotal);
    },
    //小写转大写
    smallToBig(money) {
      // 汉字的数字
      const cnNums = ["零", "壹", "贰", "叁", "肆", "伍", "陆", "柒", "捌", "玖"];
      // 基本单位
      const cnIntRadice = ["", "拾", "佰", "仟"];
      // 对应整数部分扩展单位
      const cnIntUnits = ["", "万", "亿", "兆"];
      // 对应小数部分单位
      const cnDecUnits = ["角", "分"];
      // 整数金额时后面跟的字符
      const cnInteger = "整";
      // 整型完以后的单位
      const cnIntLast = "元";
      // 最大处理的数字
      const maxNum = 9999999999999999.99;
      // 金额整数部分
      let integerNum;
      // 金额小数部分
      let decimalNum;
      // 输出的中文金额字符串
      let chineseStr = "";
      // 分离金额后用的数组，预定义
      let parts;
      if (money === "") {
        return "";
      }
      money = parseFloat(money);
      if (money >= maxNum) {
        // 超出最大处理数字
        return "";
      }
      if (money === 0) {
        chineseStr = cnNums[0] + cnIntLast + cnInteger;
        return chineseStr;
      }
      // 转换为字符串
      money = money.toString();
      if (money.indexOf(".") === -1) {
        integerNum = money;

        decimalNum = "";
      } else {
        parts = money.split(".");
        integerNum = parts[0];
        decimalNum = parts[1].substr(0, 4);
      }
      // 获取整型部分转换
      if (parseInt(integerNum, 10) > 0) {
        let zeroCount = 0;
        const IntLen = integerNum.length;
        for (let i = 0; i < IntLen; i++) {
          const n = integerNum.substr(i, 1);
          const p = IntLen - i - 1;
          const q = p / 4;
          const m = p % 4;
          if (n === "0") {
            zeroCount++;
          } else {
            if (zeroCount > 0) {
              chineseStr += cnNums[0];
            }
            // 归零
            zeroCount = 0;
            //alert(cnNums[parseInt(n)])
            chineseStr += cnNums[parseInt(n)] + cnIntRadice[m];
          }
          if (m === 0 && zeroCount < 4) {
            chineseStr += cnIntUnits[q];
          }
        }
        chineseStr += cnIntLast;
      }
      // 小数部分
      if (decimalNum !== "") {
        const decLen = decimalNum.length;
        for (let i = 0; i < decLen; i++) {
          const n = decimalNum.substr(i, 1);
          if (n !== "0") {
            chineseStr += cnNums[Number(n)] + cnDecUnits[i];
          }
        }
      }
      if (chineseStr === "") {
        chineseStr += cnNums[0] + cnIntLast + cnInteger;
      } else if (decimalNum === "") {
        chineseStr += cnInteger;
      }
      return chineseStr;
    },
    getFileInfo(res) {
      this.form.attachmentUrl = res.url;
      this.fileList = [
        {
          name: res.fileName,
          url: uploadfile,
        },
      ];
    },
    listRemove(e) {
      this.fileList = [];
      this.form.attachmentUrl = "";
    },
    getUsers() {
      this.form.userId = null;
      selectTransactorByDeptId({ deptId: this.$store.state.user.deptId }).then((res) => {
          this.usersList = res.data;
        });
    },
    /** 查询部门下拉树结构 */
    getTreeselect() {
      treeselect().then((response) => {
        this.formDeptOptions = response.data;
        this.queryDeptOptions = response.data;

        // 申请服务时买方不能选自己部门
        var items = this.formDeptOptions[0].children;
        var result = [];
        var j=0;
        for(var i=0; i<items.length; i++){
          if(items[i].id != this.$store.state.user.deptId){
            result[j] = items[i];
            j++;
          }
        }
        this.formDeptOptions[0].children = result;
      });
    },

    //切换tab
    changeTab(tabNum) {
      this.queryParams.pageNum = 1;
      this.queryParams.pageSize = 10;
      this.tab = tabNum;
      if (tabNum == 0) {
        this.queryParams.queryType = "all";
      }
      if (tabNum == 1) {
        this.queryParams.queryType = "myApply";
      }
      if (tabNum == 2) {
        this.queryParams.queryType = "myApproval";
      }
      this.getList();
    },

  }
};
</script>
<style scoped lang="scss">
  .outer-div {
    //padding: 24px;
    margin: 0 auto;
  }
  .header {
    height: 47px;
    width: 100%;
    //border-bottom: 1px solid #ebebeb;
    //margin-bottom: 24px;
  }
  ul li {
    margin: 0;
    padding: 0;
    list-style: none;
  }
  .tab-tilte {
    font-family: PingFangSC-Semibold;
    letter-spacing: 0;
    width: 90%;
    padding-left: 0;
  }
  .tab-tilte li {
    float: left;
    font-size: 16px;
    color: #999999;
    // line-height: 53px;
    text-align: center;
    margin-right: 30px;
    cursor: pointer;
  }
  /* 点击对应的标题添加对应的背景颜色 */
  .tab-tilte .active {
    color: #3385ff;
    // border-bottom: 2px solid #3385ff;
  }

  .applyDebit {
    float: right;
    width: 124px;
    border-radius: 18px;
    color: white;
    background: #1890ff;
  }
</style>
