<template>
  <div>
    <div class="sty">
      <el-page-header @back="goBack"> </el-page-header>
    </div>
    <br />
    <span>基本信息</span>
    <el-divider></el-divider>
    <!-- 表头 -->
    <div>
      <el-form ref="searchForm" :rules="rulesForm" :model="searchForm" label-width="100px" size="small" label-position="left">
        <el-row :gutter="20">
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="单据类型" prop="">
              <el-input v-model="searchForm.billType" disabled></el-input>
            </el-form-item>
          </el-col>

          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="单据来源" prop="source">
              <el-select class="selectStyle" v-model="searchForm.source" placeholder="请选择">
                <el-option value="工程押金"> </el-option>
                <el-option value="保证金"> </el-option>
                <el-option value="工程价差"> </el-option>
                <el-option value="仓储费"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="业务日期" prop="">
              <el-date-picker disabled class="selectStyle" type="datetime" placeholder="系统自动生成" default-time="23:59:59" value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="到期日" prop="endTime">
              <el-date-picker class="selectStyle" v-model="searchForm.endTime" type="datetime" placeholder="选择日期时间" default-time="23:59:59" value-format="yyyy-MM-dd HH:mm:ss">
              </el-date-picker>
            </el-form-item>
          </el-col>
          <!-- <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="总金额" prop="">
              <el-input
                disabled
                v-model="searchForm.totalAmount"
                placeholder=""
              ></el-input>
            </el-form-item>
          </el-col> -->

          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="单据状态" prop="examineStatus">
              <el-select class="selectStyle" v-model="searchForm.examineStatus" placeholder="请选择">
                <el-option value="SAVE" label="暂存"> </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="24" :sm="12" :lg="6">
            <el-form-item label="备注" prop="">
              <el-input v-model="searchForm.remark" placeholder="请输入"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
    </div>
    <span>明细</span>
    <el-divider></el-divider>
    <!-- 按钮 -->
    <div class="btn-group clearfix">
      <div class="fl">

        <el-popconfirm @onConfirm="delSeletFn" title="这是一段内容确定删除吗？">
          <el-button :disabled="selectList.length < 1" type="danger" size="mini" class="textColor delStyle" icon="el-icon-minus" slot="reference">批量删除</el-button>
        </el-popconfirm>
      </div>
      <div class="fr">
        <el-button type="primary" size="mini" @click="downLoadFn">模板</el-button>
        <el-upload class="import-btn" action="" :http-request="handleImport" :file-list="importFileList" :show-file-list="false">
          <el-button type="primary" size="mini">批量导入</el-button>
        </el-upload>

      </div>
    </div>
    <!-- 列表 -->
    <div class="mymain-container">
      <div class="table">
        <el-table v-loading="listLoading" :data="dataList" element-loading-text="Loading" border fit highlight-current-row stripe @selection-change="selectionChange" :row-class-name="rouClassNameFn" @row-click="onRowClick">
          <!-- <el-table-column align="left" label="序号">
            <template slot-scope="scope">
              {{ scope.$index + 1 }}
            </template>
          </el-table-column> -->
          <el-table-column align="center" type="selection" width="51" show-overflow-tooltip></el-table-column>
          <el-table-column align="left" label="*经销商名称" prop="customerName" min-width="280" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-select class="selectStyle" @change="changeCustomerFn($event, scope.$index)" v-model="scope.row.customerId" placeholder="请选择" filterable>
                <el-option v-for="(item, i) in customerList" :key="i" :label="item.name" :value="item.id">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="left" label="费用项目编码" prop="projectCode" min-width="160" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-input v-model="scope.row.projectCode"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="left" label="*项目费用名称" prop="projectName" min-width="160" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-input v-model="scope.row.projectName"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="left" label="*费用承担部门" prop="departmentId" min-width="160" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-input v-model="scope.row.departmentId"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="left" label="*收入部门" prop="incomeDept" min-width="160" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-input v-model="scope.row.incomeDept"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="left" label="现金钱包" prop="walletId" min-width="160" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-select filterable v-model="scope.row.customerWalletId" placeholder="请选择">
                <el-option v-for="item in scope.row.walletList" :key="item.customerWalletId" :label="item.customerWalletName" :value="item.customerWalletId">
                </el-option>
              </el-select>
            </template>
          </el-table-column>
          <el-table-column align="left" label="*发票类型" prop="invoiceType" min-width="160" show-overflow-tooltip>
            <template slot-scope="scope">
              <!-- <el-input v-model="scope.row.invoiceType"></el-input> -->
              <el-select filterable v-model="scope.row.invoiceType" placeholder="请选择">
                <el-option label="普通发票" value=""> </el-option>
                <el-option label="增值税发票" value="1"> </el-option>
                <el-option label="机票" value="P"> </el-option>
                <el-option label="火车票" value="R"> </el-option>
                <el-option label="其他运输票" value="O"> </el-option>
                <el-option label="其他" value="E"> </el-option>
              </el-select>
            </template>
          </el-table-column>
          <!-- <el-table-column
            align="center"
            label="不含税金额"
            prop="afterTaxAmount"
            min-width="160"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-input
                v-model="scope.row.afterTaxAmount"
                type="number"
              ></el-input>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            label="税额"
            prop="tax"
            min-width="160"
            show-overflow-tooltip
          >
            <template slot-scope="scope">
              <el-input type="number" v-model="scope.row.tax"></el-input>
            </template>
          </el-table-column> -->
          <el-table-column align="right" label="*总金额" prop="tax" min-width="160" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-input class='mountclass' type="number" v-model="scope.row.totalAmount"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="left" label="税率%" prop="" min-width="160" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-input type="number" :min="0" oninput="if(value>100)value=100;if(value<0)value=0" v-model="scope.row.taxRate"></el-input>
            </template>
          </el-table-column>
          <el-table-column align="left" label="备注" prop="remark" min-width="160" show-overflow-tooltip>
            <template slot-scope="scope">
              <el-input v-model="scope.row.remark"></el-input>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
    <!-- 按钮 -->
    <div class="btn-group clearfix">
      <div class="fl">
        <el-button type="primary" size="small" @click="addFn">提交审核</el-button>
        <el-button type="primary" size="small" @click="resetFn">重置</el-button>
      </div>
      <div class="fr">
        <el-button type="primary" size="small" @click="addRowFn">添加行</el-button>
        <el-button type="primary" size="small" @click="delRowFn">删除行</el-button>
      </div>
    </div>

    <!-- 提示 -->
    <el-dialog title="提示" :visible.sync="dialogVisible" width="30%">
      <ul class="ulStyle" v-for="(v, i) in messageList" :key="i">
        <li>{{ v }},现金钱包余额不足,请确认是否继续提交此单据</li>
      </ul>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisibleCancel">取 消</el-button>
        <el-button type="primary" @click="dialogVisibleOK">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getCustomerList,
  getFinanceCustomerList,
  getFinanceOtherReceAdd,
  getFinanceOtherReceApply,
  getFinanceOtherReceList,
} from "@/api/finance/receivable_list";
import { downloadFiles, handleImport } from "@/utils/util";
export default {
  data() {
    return {
      importFileList: [],
      messageList: [],
      dialogVisible: false,
      searchForm: {
        source: "",
        billType: "其他应收单",
        examineStatus: "SAVE",
        endTime: "",
        remark: "",
      },
      rulesForm: {
        source: [
          { required: true, trigger: "change", message: "请选择单据来源" },
        ],
        examineStatus: [
          { required: true, trigger: "change", message: "请选择单据状态" },
        ],
        endTime: [
          { required: true, trigger: "change", message: "请选择到期日期" },
        ],
      },
      dataList: [],
      customerList: [], //经销商数据
      listLoading: false, // 列表加载loading
      walletList: [], //现金钱包数据
      delIndex: null,
      selectList: [],
    };
  },
  created() {
    this.getCustomerList();
  },
  methods: {
    //删除
    delSeletFn() {
      // console.log(this.dataList);
      this.selectList.sort(function (a, b) {
        return b - a;
      });
      // console.log(this.selectList);

      for (let index = 0; index < this.selectList.length; index++) {
        // console.log(index);
        this.dataList.splice(this.selectList[index], 1);
      }
    },
    //选择项改变
    selectionChange(v) {
      // console.log(v);
      this.selectList = v.map((v) => v.index);
      // console.log(this.selectList);
    },
    // 导入
    async handleImport(param) {
      const file = param.file;

      const formData = new FormData();
      formData.append("file", file);

      let result = await handleImport("/finance/rece/import/data", formData);

      // console.log(result);
      this.importFileList = [];
      if (result.code == 200) {
        this.$message.success("导入成功");
        // this.dataList.unshift(result.data);

        this.searchForm.source = result.data.source;
        this.searchForm.endTime = result.data.endTime;
        // this.searchForm.examineStatus = result.data.examineStatus;
        this.searchForm.examineStatus = "暂存";
        this.searchForm.remark = result.data.remark;
        let Arr = result.data.items;
        for (let v = 0; v < Arr.length; v++) {
          const res = await getFinanceCustomerList({
            customerId: Arr[v].customerId,
            type: "COMMONLY",
          });
          this.dataList.push({
            customerNumber: Arr[v].customerNumber,
            customerName: Arr[v].customerName,
            customerId: Arr[v].customerId,
            projectCode: Arr[v].projectCode,
            projectName: Arr[v].projectName,
            departmentId: Arr[v].departmentId,
            customerWalletId: Arr[v].customerWalletId,
            // invoiceType: Arr[v].invoiceType,
            invoiceType: Arr[v].invoiceType ? Arr[v].invoiceType : "",
            incomeDept: Arr[v].incomeDept,
            totalAmount: Arr[v].totalAmount,
            taxRate: Arr[v].taxRate,
            walletId: Arr[v].valletId,
            walletList: res.data,
            remark: Arr[v].remark,
          });
        }
      } else {
        this.$message.error(result.message);
        // this.$message.error(1231);
      }
    },
    //下载模板
    async downLoadFn() {
      downloadFiles("/finance/other/rec/download");
    },
    //取消
    async dialogVisibleCancel() {
      this.dialogVisible = false;
    },
    //确定
    async dialogVisibleOK() {
      this.dialogVisible = false;
      await getFinanceOtherReceAdd({
        items: this.dataList,
        ...this.searchForm,
        isContinue: true,
      });
      const res = await getFinanceOtherReceList({ pageSize: 1, pageNum: 1 });
      await getFinanceOtherReceApply({ id: res.data.records[0].id });
      this.$message.success("提审成功");
      this.$emit("updateList");
      this.$parent.showPage = 1;
      this.resetFn();
    },
    // // 不含税金额改变事件
    // changeAfterTaxAmount(v, i, sl) {
    //   // console.log(v, i);
    //   // let rule = /(^-?[1-9](\d+)?(\.\d{1,2})?$)|(^-?0$)|(^-?\d\.\d{1,2}$)/;
    //   // console.log();
    //   // if (!rule.test(v)) {
    //   //   this.$message.error("请输入正确的不含税金额");
    //   //   return;
    //   // }
    //   //税额
    //   let tax = (v * (sl / 100)).toFixed(2);
    //   // console.log(tax, "税额");
    //   //总金额
    //   let totalAmount = (v * 1 + tax * 1).toFixed(2);
    //   // console.log(totalAmount, "总金额");

    //   this.$set(this.dataList[i], "tax", tax);
    //   this.$set(this.dataList[i], "totalAmount", totalAmount);
    // },
    //重置
    resetFn() {
      this.searchForm = {};
    },
    rouClassNameFn({ row, rowIndex }) {
      //把每一行的索引放进row
      row.index = rowIndex;
    },
    onRowClick(row, event, column) {
      this.delIndex = row.index;
    },
    //删除行
    delRowFn() {
      this.dataList.splice(this.delIndex, 1);
    },

    //新增
    async addFn() {
      await this.$refs.searchForm.validate();
      if (this.dataList.length == 0) {
        this.$message.error("请添加数据");
        return;
      }
      let aaa = this.dataList.find((v) => {
        if (v.customerId == "") {
          this.$message.error("请选择经销商");
          return v;
        }
        if (v.departmentId == "") {
          this.$message.error("请输入费用承担部门");
          return v;
        }
        if (v.incomeDept == "") {
          this.$message.error("请输入收入部门");
          return v;
        }
        if (!v.customerWalletId) {
          this.$message.error("请选择现金钱包");
          return v;
        }
        if (v.totalAmount == "") {
          this.$message.error("请输入总金额");
          return v;
        }
      });
      console.log(aaa);
      if (aaa != undefined) {
        return;
      }
      // console.log(this.dataList, 7777);
      this.dataList.forEach((v) => {
        let res = this.customerList.filter((i) => i.id == v.customerId);
        console.log(res);
        v.customerName = res[0].name;
        v.customerNumber = res[0].number;
        let res2 = v.walletList.filter(
          (j) => j.customerWalletId == v.customerWalletId
        );
        // console.log(res2, "res2");
        // v.customerWalletId = res2[0].customerWalletId;
        v.walletId = res2[0].walletRebateId;
      });
      // console.log(this.dataList, 888888);

      let res = await getFinanceOtherReceAdd({
        items: this.dataList,
        ...this.searchForm,
      });
      if (res.code == 201) {
        this.dialogVisible = true;
        this.messageList = res.data;
      }
      if (res.code == 200) {
        const res = await getFinanceOtherReceList({ pageSize: 1, pageNum: 1 });
        await getFinanceOtherReceApply({ id: res.data.records[0].id });
        this.$message.success("提审成功");
        this.$emit("updateList");
        this.$parent.showPage = 1;
        this.resetFn();
      }
    },
    //选择经销商名称事件
    async changeCustomerFn(v, index) {
      console.log(v, 322311);
      const res = await getFinanceCustomerList({
        customerId: v,
        type: "COMMONLY",
      });
      this.$set(this.dataList[index], "walletList", res.data);
      console.log(this.dataList, "kkk");
      // this.walletList = res.data;
    },
    //获取经销商数据
    async getCustomerList() {
      const res = await getCustomerList({ pageNum: 1, pageSize: -1 });
      this.customerList = res.data.records;
    },
    //添加行数据
    addRowFn() {
      this.dataList.push({
        customerId: "",
        projectCode: "FYXM01_SYS",
        projectName: "材料成本",
        departmentId: "",
        customerWalletId: "",
        invoiceType: "",
        incomeDept: "",
        // afterTaxAmount: "",
        // tax: "",
        totalAmount: "",
        taxRate: 13,
      });
    },
    goBack() {
      this.$parent.showPage = 1;
    },
  },
};
</script>

<style lang="scss" scoped>
.import-btn {
  display: inline-block;
  margin-left: 10px;
}
::v-deep .mountclass {
  input {
    text-align: right;
  }
}
::v-deep .el-dialog__body {
  padding: 0 20px;
}
.selectStyle {
  width: 100%;
}
.mar {
  margin-top: 20px;
}
.ulStyle {
  list-style: simp-chinese-informal;
  li {
    height: 30px;
    line-height: 30px;
  }
}
</style>
