<template>
  <div>
    <basic-container v-show="isShow">
      <avue-crud :option="option" :table-loading="loading" :data="data" :page.sync="page" :permission="permissionList"
        id="out-table" :header-cell-class-name="headerClassName" :before-open="beforeOpen" v-model="form" ref="crud"
        @row-update="rowUpdate" @row-save="rowSave" @row-del="rowDel" @search-change="searchChange"
        @search-reset="searchReset" @selection-change="selectionChange" @current-change="currentChange"
        @size-change="sizeChange" @refresh-change="refreshChange" :search.sync="query"
        @resetColumn="resetColumnTwo('crud', 'option', 'optionBack', 316.1)"
        @saveColumn="saveColumnTwo('crud', 'option', 'optionBack', 316.1)" @on-load="onLoad"
        @expand-change="expandChange">
        <template slot="expand" slot-scope="{row}">
          <finstlbillsitems :tableData="row.finStlBillsItemsList || []" :brfalse="false"></finstlbillsitems>
        </template>
        <tempalte slot="feeCnNameSearch">
          <dic-select v-model="query.feeCnName" placeholder="费用名称" key="id" label="cnName" res="records"
            url="/blade-los/bfees/list" :filterable="true" :remote="true" dataName="cnName"></dic-select>
        </tempalte>
        <template slot="menuLeft">
          <el-button type="success" size="small" icon="el-icon-plus" plain @click="newbillFun">新建付费申请
          </el-button>
          <el-button type="danger" size="small" icon="el-icon-delete" plain @click="handleDelete">一键删除
          </el-button>
        </template>
        <template slot="menu" slot-scope="{row}">
          <el-button type="text" size="small" @click="editFun(row)">编辑
          </el-button>
          <!--:disabled="saberUserInfo.role_name.indexOf('允许修改他人业务') == -1?saberUserInfo.user_id != row.createUser:false"-->
          <el-button type="text" size="small"
            v-if="saberUserInfo.role_name.indexOf('admin') == -1 ? saberUserInfo.role_name.indexOf('允许修改他人业务') == -1 ? saberUserInfo.user_id == row.createUser : true : true"
            :disabled="row.status == 1 || row.status == 3" @click="rowDel(row)">删除
          </el-button>
        </template>
        <template slot="billNo" slot-scope="{row}">
          <span class="pointerClick" @click="editFun(row)">{{ row.billNo }}
          </span>
        </template>
      </avue-crud>
    </basic-container>

    <finstlbillsDetails ref="finstlbillsDetails" v-if="!isShow" :editSave="editSave" @goBack="goBack"
      @toAddEdit="toAddEdit" :key="datekey">
    </finstlbillsDetails>

  </div>
</template>

<script>
import { finstlbillsList, finstlbillsDetail, finstlbillsSubmit, finstlbillsRemove, finstlbillsitemsList } from "@/api/iosBasicData/finstlbills";
import { mapGetters } from "vuex";
import finstlbillsDetails from '@/views/iosBasicData/PaymentApplication/finstlbillsDetails.vue'
import { getWorkDicts } from "@/api/system/dictbiz";
import finstlbillsitems from "@/views/iosBasicData/PaymentApplication/assembly/finstlbillsitems.vue";
import { getRateList } from "@/api/iosBasicData/rateManagement";
import reports from "@/views/iosBasicData/SeafreightExportF/bills/assembly/reports.vue";
import dicSelect from "@/components/dicSelect/main";
export default {
  components: { finstlbillsitems, finstlbillsDetails, reports, dicSelect },
  data() {
    return {
      datekey: Date.now(),
      // 详情页面和列表切换
      isShow: true,
      form: {},
      query: {},
      loading: true,
      page: {
        pageSize: 10,
        currentPage: 1,
        total: 0
      },
      selectionList: [],
      option: {},
      optionBack: {
        height: 'auto',
        calcHeight: 30,
        tip: false,
        searchShow: true,
        searchMenuSpan: 6,
        border: true,
        index: true,
        viewBtn: true,
        selection: true,
        dialogClickModal: false,
        menuWidth: 100,
        expand: true,
        rowKey: 'id',
        column: [
          {
            label: "单据编号",
            prop: "billNo",
            search: true,
            width: "120",
            overHidden: true
          },
          {
            label: "付费对象",
            prop: "corpCnName",
            search: true,
            width: "120",
            searchOrder: 1,
            overHidden: true
          },
          {
            label: "银行账号",
            prop: "bankAccountNo",
            width: "120",
            overHidden: true
          },
          {
            label: "账户名称",
            prop: "bankAccountName",
            width: "120",
            overHidden: true
          },
          {
            label: "账户银行",
            prop: "bankAccountBank",
            width: "120",
            overHidden: true
          },
          {
            label: "付费事由",
            prop: "remarks",
            overHidden: true,
            search: true,
          },
          {
            label: "收款情况",
            prop: "collectionSituation",
            search: true,
            width: "120",
            overHidden: true
          },
          {
            label: "审核状态",
            prop: "status",
            search: true,
            width: "120",
            type: 'select',
            dicData: [
              {
                label: '未审核',
                value: 0
              }, {
                label: '审核中',
                value: 1
              }, {
                label: '已审核',
                value: 3
              }, {
                label: '驳回',
                value: 4
              }
            ],
            overHidden: true
          },
          {
            label: "费用名称",
            prop: "feeCnName",
            width: "140",
            search: true,
            overHidden: true,
          },
          {
            label: "预计收回",
            prop: "estimatedTime",
            type: 'date',
            format: "yyyy-MM-dd",
            valueFormat: 'yyyy-MM-dd',
            width: "120",
            overHidden: true
          },
          {
            label: "预计开始收回",
            prop: "estimatedTimeStart",
            search: true,
            overHidden: true,
            searchLabelWidth: "100",
            hide: true,
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
          },
          {
            label: "预计结束收回",
            prop: "estimatedTimeEnd",
            search: true,
            overHidden: true,
            searchLabelWidth: "100",
            hide: true,
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
          },
          {
            label: "应付(CNY)",
            prop: "amountCr",
            width: "160",
            overHidden: true
          },
          {
            label: "合计应付(CNY)",
            prop: "amountCrLoc",
            width: "160",
            overHidden: true
          },
          {
            label: "应收(CNY)",
            prop: "amountDr",
            width: "160",
            overHidden: true
          },
          {
            label: "合计应收(CNY)",
            prop: "amountDrLoc",
            width: "160",
            overHidden: true
          },
          // {
          //   label: "业务日期",
          //   prop: "billDate",
          //   overHidden: true,
          //   width: "150",
          // },
          {
            label: "业务开始日期",
            prop: "billDateStart",
            width: "140",
            overHidden: true,
            search: true,
            hide: true,
            searchLabelWidth: "100",
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
          },
          {
            label: "业务结束日期",
            prop: "billDateEnd",
            width: "140",
            overHidden: true,
            search: true,
            hide: true,
            searchLabelWidth: "100",
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
          },
          // {
          //     label: "业务日期",
          //     prop: "billDateList",
          //     search:true,
          //     hide:true,
          //     searchProp: "billDateList",
          //     type: "date",
          //     overHidden: true,
          //     width: 100,
          //     searchRange: true,
          //     searchDefaultTime: ["00:00:00", "23:59:59"],
          //     format: "yyyy-MM-dd",
          //     valueFormat: "yyyy-MM-dd HH:mm:ss"
          // },
          {
            label: "费用收付",
            prop: "dc",
            search: true,
            type: 'select',
            dicData: [
              {
                label: '收',
                value: 'D'
              }, {
                label: '付',
                value: 'C'
              }
            ],
            overHidden: true
          },
          {
            label: "币种",
            prop: "curCode",
            search: true,
            type: 'select',
            dicData: [],
            dicUrl: '/api/blade-los/bcurrency/page?current=1&size=20',
            props: {
              label: "code",
              value: "id"
            },
            overHidden: true
          },
          {
            label: "JOB NO",
            prop: "businessNo",
            width: "120",
            search: true,
            searchOrder: 3,
            overHidden: true
          },
          {
            label: "ACCT NO",
            prop: "accountNo",
            width: "100",
            search: true,
            searchOrder: 5,
            overHidden: true
          },
          {
            label: "MB/L NO",
            prop: "mblno",
            search: true,
            searchOrder: 2,
            overHidden: true
          },
          {
            label: "HB/L NO",
            prop: "hblno",
            search: true,
            searchOrder: 4,
            overHidden: true
          },
          {
            label: "对账单号",
            prop: "checkNo",
            search: true,
            width: "100",
            searchOrder: 6,
            overHidden: true
          },
          {
            label: "船名",
            prop: "vesselCnName",
            search: true,
            searchOrder: 7,
            overHidden: true
          },
          {
            label: "航次",
            prop: "voyageNo",
            search: true,
            searchOrder: 8,
            overHidden: true
          },
          {
            label: "业务类型",
            prop: "businessTypes",
            width: "120",
            overHidden: true,
            type: 'select',
            multiple: true,
            dicData: [
              {
                label: '海运出口',
                value: 'SE'
              }, {
                label: '海运进口',
                value: 'SI'
              }
            ],
          },
        ]
      },
      data: [],
      editSave: false, // 编辑保存打印状态
      saberUserInfo: {}, // 当前登录人个人信息
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.finstlbills_add, false),
        viewBtn: this.vaildData(this.permission.finstlbills_view, false),
        delBtn: this.vaildData(this.permission.finstlbills_delete, false),
        editBtn: this.vaildData(this.permission.finstlbills_edit, false)
      };
    },
    ids() {
      let ids = [];
      this.selectionList.forEach(ele => {
        ids.push(ele.id);
      });
      return ids.join(",");
    }
  },
  async created() {
    // 获取当前登录人个人信息
    this.saberUserInfo = JSON.parse(localStorage.getItem('saber-userInfo')).content
    this.option = await this.getColumnData(this.getColumnName(316.1), this.optionBack);
    if (this.$route.query.billId) {
      // 从审批里查看跳进来的
      this.editFun({ id: this.$route.query.billId })
    }
    this.$store.commit('FFQSF_IN_DETAIL')
    // this.dictionaryfun() // 获取字典数据
    this.getRateListfun() // 币别数据

  },
  activated() {
    if (this.$route.query.id) {
      setTimeout(() => {
        if (!this.$store.getters.payAppStatus) {
          this.editFun(this.$route.query)
        }
      }, 200);
    }
    if (this.$route.query.mblno) {
      setTimeout(() => {
        if (!this.$store.getters.payAppStatus) {
          this.newbillFun()
        }
      }, 200);
    }
  },
  methods: {
    // 展开行
    expandChange(row, expendList) {
      finstlbillsitemsList(1, 20, { pid: row.id }).then(res => {
        row.finStlBillsItemsList = res.data.data.records.map(item => {
          if (item.currentStlCurCode == 'CNY') {
            // 发票
            this.$set(item, 'currentInvoiceAmountRMB', item.currentInvoiceAmount)
            // 应结算金额
            this.$set(item, 'amountRMB', item.amount)
            // 已结算金额
            this.$set(item, 'stlTtlAmountRMB', item.stlTtlAmount)
            // 本次金额
            this.$set(item, 'currentStlAmountRMB', item.currentStlAmount)
          } else {
            // 发票
            this.$set(item, 'currentInvoiceAmountUSD', item.currentInvoiceAmount)
            // 应结算金额
            this.$set(item, 'amountUSD', item.amount)
            // 已结算金额
            this.$set(item, 'stlTtlAmountUSD', item.stlTtlAmount)
            // 本次金额
            this.$set(item, 'currentStlAmountUSD', item.currentStlAmount)
          }
          return item
        })
      })
    },
    // 新建账单
    newbillFun() {
      this.isShow = false
      this.editSave = false
      // this.$refs.finstlbillsDetails
      this.$store.commit("IN_PAYAPP_DETAIL");
    },
    toAddEdit() {
      this.datekey = Date.now()
      this.isShow = false
      this.editSave = false
    },
    // 编辑
    editFun(row) {
      this.isShow = false
      this.editSave = true
      this.$nextTick(() => {
        this.$refs.finstlbillsDetails.finstlbillsDetailfun(row.id)
      })
      this.$store.commit("IN_PAYAPP_DETAIL");
    },
    // 详情的返回列表
    goBack() {
      // 初始化数据
      // this.detailData = this.$options.data().detailData;
      if (JSON.stringify(this.$route.query) != "{}") {
        this.$router.$avueRouter.closeTag();
        this.$router.push({
          path: "/iosBasicData/PaymentApplication/index"
        });
      }
      this.isShow = true;
      this.onLoad(this.page, this.search);
      this.$store.commit("OUT_PAYAPP_DETAIL");
    },
    // 添加
    rowSave(row, done, loading) {
      finstlbillsSubmit(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    // 保存
    rowUpdate(row, index, done, loading) {
      finstlbillsSubmit(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        console.log(error);
      });
    },
    // 删除
    rowDel(row) {
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return finstlbillsRemove(row.id);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
        });
    },
    // 批量删除
    handleDelete() {
      if (this.selectionList.length === 0) {
        this.$message.warning("请选择至少一条数据");
        return;
      }
      // 判断是否可以编辑别人业务 true 就没有权限
      if (this.ModifyOthersfun()) return;
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return finstlbillsRemove(this.ids);
        })
        .then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          this.$refs.crud.toggleSelection();
        });
    },
    // 判断是否可以编辑别人业务
    ModifyOthersfun() {
      let sumArr = []
      const h = this.$createElement
      // 判断是否有权限
      if (this.saberUserInfo.role_name.indexOf('允许修改他人业务') != -1) return false
      // 当前登录人和选择的创建人对比是不是一个人
      for (let item of this.selectionList) {
        if (this.saberUserInfo.user_id != item.createUser) {
          sumArr.push(h('p', `你没有"允许修改他人业务"权限,请重新选择数据`))
        }
      }
      if (sumArr.length != 0) {
        this.$confirm('提示', {
          message: h('div', sumArr),
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).catch(err => { })
        return true
      }
    },
    // 详情
    beforeOpen(done, type) {
      if (["edit", "view"].includes(type)) {
        finstlbillsDetail(this.form.id).then(res => {
          this.form = res.data.data;
        });
      }
      done();
    },
    searchReset() {
      this.query = {};
      this.onLoad(this.page);
    },
    searchChange(params, done) {
      this.query = params;
      this.page.currentPage = 1;
      this.onLoad(this.page, this.query);
      done();
    },
    selectionChange(list) {
      this.selectionList = list;
    },
    selectionClear() {
      this.selectionList = [];
      this.$refs.crud.toggleSelection();
    },
    currentChange(currentPage) {
      this.page.currentPage = currentPage;
    },
    sizeChange(pageSize) {
      this.page.pageSize = pageSize;
    },
    refreshChange() {
      this.onLoad(this.page, this.query);
    },
    onLoad(page, params = {}) {
      this.loading = true;
      finstlbillsList(
        page.currentPage,
        page.pageSize,
        { ...Object.assign(params, this.query), businessType: 'FFSQ' },
      ).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records.map(item => {
          item.isApproved = item.isApproved + ''
          item.isSignfor = item.isSignfor + ''
          item.isChecked = item.isChecked + ''
          item.isCleared = item.isCleared + ''
          item.isInvoice = item.isInvoice + ''
          item.isTax = item.isTax + ''
          item.corpIsSigned = item.corpIsSigned + ''
          return item
        })
        this.loading = false;
        this.selectionClear();
      });
    },

    // 获取字典数据
    dictionaryfun() {
      // 全部是否
      getWorkDicts('ifInvoice').then(res => {
        // this.findObject(this.option.column, "isApproved").dicData = res.data.data
        // this.findObject(this.option.column, "isSignfor").dicData = res.data.data
        this.findObject(this.option.column, "isChecked").dicData = res.data.data
        this.findObject(this.option.column, "isCleared").dicData = res.data.data
      })
      // 是否开发票
      // getWorkDicts('invoice_los').then(res=>{
      //     this.findObject(this.option.column, "isInvoice").dicData = res.data.data
      // })
      // 是否
      // getWorkDicts('ifInvoice').then(res=>{
      //     // this.findObject(this.option.column, "corpIsSigned").dicData = res.data.data
      //     this.findObject(this.option.column, "isTax").dicData = res.data.data
      // })
    },
    // 获取币别数据
    getRateListfun(cnName) {
      getRateList({ current: 1, size: 20, cnName }).then(res => {
        this.findObject(this.option.column, "curCode").dicData = res.data.data.records
      })
    },

    //自定义列保存
    async saveColumnTwo(ref, option, optionBack, code) {
      /**
       * 已定义全局方法，直接使用，saveColumnData保存列数据方法,参数传值(表格名称，当前表格的option数据)
       * 已定义全局方法，直接使用，getColumnName方法用来获取枚举值，参数根据自己定义的code值获取中文名
       * 一定要执行异步操作，要等接口成功返回，才能执行下一行代码
       */
      const inSave = await this.saveColumnData(this.getColumnName(code), this[option]);
      if (inSave) {
        this.$message.success("保存成功");
        //关闭窗口
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
    },
    //自定义列重置
    async resetColumnTwo(ref, option, optionBack, code) {
      this[option] = this[optionBack];
      const inSave = await this.delColumnData(this.getColumnName(code), this[optionBack]);
      if (inSave) {
        this.$message.success("重置成功");
        this.$refs[ref].$refs.dialogColumn.columnBox = false;
      }
    },

    // 更改表格颜色
    headerClassName(tab) {
      //颜色间隔
      let back = ""
      if (tab.columnIndex >= 0 && tab.column.level === 1) {
        if (tab.columnIndex % 2 === 0) {
          back = "back-one"
        } else if (tab.columnIndex % 2 === 1) {
          back = "back-two"
        }
      }
      return back;
    },



  }
};
</script>

<style scoped>
::v-deep#out-table .back-one {
  background: #ecf5ff !important;
  text-align: center;
}

::v-deep#out-table .back-two {
  background: #ecf5ff !important;
  text-align: center;
}

/deep/ .el-col-md-8 {
  width: 24.33333%;
}

.pointerClick {
  cursor: pointer;
  color: #1e9fff;
}
</style>
