<template>
  <div>
      <basic-container>
          <avue-crud :option="option"
                     :table-loading="loading"
                     :data="data"
                     :page.sync="page"
                     :search.sync="query"
                     :permission="permissionList"
                     :before-open="beforeOpen"
                     v-model="form"
                     ref="crud"
                     id="out-table"
                     :header-cell-class-name="headerClassName"
                     @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"
                     @resetColumn="resetColumnTwo('crud', 'option', 'optionBack', 329)"
                     @saveColumn="saveColumnTwo('crud', 'option', 'optionBack', 329)"
                     @on-load="onLoad" >
              <template slot="menuLeft">
                  <el-button type="primary"
                             size="small"
                             plain @click="initializationfun" >初始入账
                  </el-button>
                  <el-button type="success"
                             size="small"
                             plain >导出
                  </el-button>
                  <el-button type="danger"
                             size="small"
                             icon="el-icon-delete"
                             plain
                             v-if="permission.fingenleg_delete"
                             @click="handleDelete">删 除
                  </el-button>
              </template>
              <template slot-scope="{disabled,size}" slot="startCodeSearch">
                  <search-query :datalist="startCodeData"
                                :selectValue="query.startCode"
                                :filterable="true"
                                :clearable="true"
                                :remote="true"
                                :buttonIf="false"
                                :forParameter="{key:'id',label:'code',value:'code'}"
                                @corpFocus="startCodeDatafun"
                                @remoteMethod="startCodeDatafun"
                                @corpChange="corpChange($event,'startCode')">
                  </search-query>
              </template>
              <template slot-scope="{disabled,size}" slot="endCodeSearch">
                  <search-query :datalist="endCodeData"
                                :selectValue="query.endCode"
                                :filterable="true"
                                :clearable="true"
                                :remote="true"
                                :buttonIf="false"
                                :forParameter="{key:'id',label:'code',value:'code'}"
                                @corpFocus="endCodeDatafun"
                                @remoteMethod="endCodeDatafun"
                                @corpChange="corpChange($event,'endCode')">
                  </search-query>
              </template>
              <template slot-scope="{disabled,size}" slot="isYearMothSearch">
                  <el-checkbox v-model="query.isYearMoth" :true-label="1" :false-label="0" @change="isYearMothfun" ></el-checkbox>
              </template>
              <template slot-scope="{disabled,size}" slot="isBalanceSearch">
                  <el-checkbox v-model="query.isBalance" :true-label="1" :false-label="0" ></el-checkbox>
              </template>
              <template slot-scope="{disabled,size}" slot="isForeignDetermineSearch">
                  <el-checkbox v-model="isForeignDetermine"  @change="isForeignDeterminefun" ></el-checkbox>
              </template>
          </avue-crud>
      </basic-container>
  </div>
</template>

<script>
import {
    fingenlegList,
    fingenlegDetail,
    fingenlegSubmit,
    fingenlegRemove,
    fingenlegInitialization
} from "@/api/iosBasicData/fingenleg";
import {accountsList} from "@/api/iosBasicData/accounts";
  import {mapGetters} from "vuex";
import SearchQuery from "@/components/iosbasic-data/searchquery.vue";
import {CurrentMonth, dateFormat, defaultDate4} from "@/util/date";

  export default {
      components: {SearchQuery},
    data() {
      return {
        form: {},
        query: {
            isYearMoth:0,
            isBalance:0,
            accyear:defaultDate4(), // 默认当年
            startDate:CurrentMonth(new Date(),'yyyy-MM'), // 开始日期
            endDate:dateFormat(new Date(),'yyyy-MM'), // 结束日期
        },
        isForeignDetermine:false, // 是否外币
        startCodeData:[], // 开始科目数据
        endCodeData:[], // 结束科目数据
        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: false,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          menu:false,
          rowKey:'id',
          rowParentKey:'pid',
          defaultExpandAll:true,
          column: [
            {
              label: "年",
              prop: "accyear",
              width:'80',
              index:1,
              overHidden:true,
            },
            {
              label: "月",
              prop: "accmonth",
                width:'40',
                index:2,
              overHidden:true,
            },
            {
              label: "科目代码",
              prop: "accCode",
                index:3,
              overHidden:true,
            },
            {
              label: "科目名称",
              prop: "fullName",
                index:4,
              overHidden:true,
            },
            {
                label: "科目方向",
                prop: "accDc",
                index:5,
                type: 'select',
                dicData:[
                    {
                        label:'借方',
                        value:'D'
                    },{
                        label:'贷方',
                        value:'C'
                    },
                ],
                overHidden:true,
            },
            {
              label: "摘要",
              prop: "descr",
                index:6,
              overHidden:true,
            },
            {
                label: "开始科目",
                prop: "startCode",
                overHidden:true,
                search:true,
                hide:true,
                searchslot:true,
            },
            {
                label: "结束科目",
                prop: "endCode",
                overHidden:true,
                search:true,
                hide:true,
                searchslot:true,
            },
            {
                label: "开始日期",
                prop: "startDate",
                search:true,
                overHidden:true,
                hide:true,
                type: "month",
                format: "yyyy-MM",
                valueFormat: "yyyy-MM",
            },
            {
                label: "结束日期",
                prop: "endDate",
                search:true,
                overHidden:true,
                hide:true,
                type: "month",
                format: "yyyy-MM",
                valueFormat: "yyyy-MM",
            },
            {
              label: "币种",
              prop: "curCode",
              hide:true,
              search:true,
              dicData:[
                  {
                      label:'CNY',
                      value:'CNY'
                  },{
                      label:'USD',
                      value:'USD'
                  },
              ],
              overHidden:true,
            },
            {
                label: "无发生额显示本月本年累计",
                prop: "isYearMoth",
                hide:true,
                search:true,
                searchslot:true,
                searchLabelWidth:'160',
                searchSpan:4,
            },
            {
                label: "无余额无发生显示",
                prop: "isBalance",
                hide:true,
                search:true,
                searchslot:true,
                searchLabelWidth:'120',
                searchSpan:4,
            },
            {
                label: "显示外币",
                prop: "isForeignDetermine",
                hide:true,
                search:true,
                searchslot:true,
                searchSpan:3,
            },
            {
              label: "本期借方金额",
              prop: "amountDr",
                index:7,
                width:'100',
                overHidden:true,
            },
            {
              label: "本期贷方金额",
              prop: "amountCr",
                index:8,
                width:'100',
                overHidden:true,
            },
            {
              label: "本期余额",
              prop: "amountBlc",
                index:9,
              overHidden:true,
            },
            {
                label: "方向",
                prop: "dc",
                index:10,
                type: 'select',
                dicData:[
                    {
                        label:'借方',
                        value:'D'
                    },{
                        label:'贷方',
                        value:'C'
                    },
                ],
                overHidden:true,
            },

          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.fingenleg_add, false),
          viewBtn: this.vaildData(this.permission.fingenleg_view, false),
          delBtn: this.vaildData(this.permission.fingenleg_delete, false),
          editBtn: this.vaildData(this.permission.fingenleg_edit, false)
        };
      },
      ids() {
        let ids = [];
        this.selectionList.forEach(ele => {
          ids.push(ele.id);
        });
        return ids.join(",");
      }
    },
    async created() {
        this.option = await this.getColumnData(this.getColumnName(329), this.optionBack);
    },
    methods: {
          // 下拉监听
        corpChange(value,name){
            this.$set(this.query,name,value)
        },
        // 获取科目类型数据
        startCodeDatafun(code){
            accountsList(1,10,{code,isDetail:1}).then(res=>{
                this.startCodeData = res.data.data.records
            })
        },
        endCodeDatafun(code){
            accountsList(1,10,{code,isDetail:1}).then(res=>{
                this.endCodeData = res.data.data.records
            })
        },
        // 无发生额显示本月本年累计 点击
        isYearMothfun(){
            let obj = JSON.parse(JSON.stringify(this.query))
            if (this.query.isYearMoth) {
                this.findObject(this.option.column, "amountDr").label = '本年借方金额'
                this.findObject(this.option.column, "amountDr").prop = 'amountYearDr'
                this.findObject(this.option.column, "amountCr").label = '本年贷方金额'
                this.findObject(this.option.column, "amountCr").prop = 'amountYearCr'
                if (this.isForeignDetermine) {
                    this.findObject(this.option.column, "amountDrUsd").label = '本年借方外币金额'
                    this.findObject(this.option.column, "amountDrUsd").prop = 'amountYearDrUsd'
                    this.findObject(this.option.column, "amountCrUsd").label = '本年贷方外币金额'
                    this.findObject(this.option.column, "amountCrUsd").prop = 'amountYearCrUsd'
                }
            }else {
                this.findObject(this.option.column, "amountYearDr").label = '本期借方金额'
                this.findObject(this.option.column, "amountYearDr").prop = 'amountDr'
                this.findObject(this.option.column, "amountYearCr").label = '本期贷方金额'
                this.findObject(this.option.column, "amountYearCr").prop = 'amountCr'
                if (this.isForeignDetermine) {
                    this.findObject(this.option.column, "amountYearDrUsd").label = '本期借方外币金额'
                    this.findObject(this.option.column, "amountYearDrUsd").prop = 'amountDrUsd'
                    this.findObject(this.option.column, "amountYearCrUsd").label = '本期贷方外币金额'
                    this.findObject(this.option.column, "amountYearCrUsd").prop = 'amountCrUsd'
                }
            }
            this.query = JSON.parse(JSON.stringify(obj))
        },
        // 是否外币点击
       isForeignDeterminefun(){
           let obj = JSON.parse(JSON.stringify(this.query))
          if (this.isForeignDetermine) {
              this.option.column.push(
                  {
                      label: '币种',
                      prop: 'curCode',
                      index:11,
                      overHidden: true,
                  },
                  {
                      label: '本期借方外币金额',
                      prop: 'amountDrUsd',
                      width:'120',
                      index:12,
                      overHidden: true,
                  },{
                      label: '本期贷方外币金额',
                      prop: 'amountCrUsd',
                      width:'120',
                      index:13,
                      overHidden: true,
                  },{
                      label: '本期外币余额',
                      prop: 'amountUsdBlc',
                      width:'100',
                      index:14,
                      overHidden: true,
                  })
              if (this.query.isYearMoth) {
                  this.findObject(this.option.column, "amountDrUsd").label = '本年借方外币金额'
                  this.findObject(this.option.column, "amountDrUsd").prop = 'amountYearDrUsd'
                  this.findObject(this.option.column, "amountCrUsd").label = '本年贷方外币金额'
                  this.findObject(this.option.column, "amountCrUsd").prop = 'amountYearCrUsd'
              }
              this.query = JSON.parse(JSON.stringify(obj))
          }else {
              this.option = JSON.parse(JSON.stringify(this.optionBack))
              this.query = JSON.parse(JSON.stringify(obj))
              if (this.query.isYearMoth) {
                  this.findObject(this.option.column, "amountDr").label = '本年借方金额'
                  this.findObject(this.option.column, "amountDr").prop = 'amountYearDr'
                  this.findObject(this.option.column, "amountCr").label = '本年贷方金额'
                  this.findObject(this.option.column, "amountCr").prop = 'amountYearCr'
              }
          }
      },
      // 初始入账
      initializationfun(){
          fingenlegInitialization().then(res=>{
              this.page.currentPage = 1;
              this.onLoad(this.page, this.query);
          })
      },
      rowSave(row, done, loading) {
        fingenlegSubmit(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        fingenlegSubmit(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 fingenlegRemove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return fingenlegRemove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          fingenlegDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      searchReset() {
        this.query = {
            isYearMoth:0,
            isBalance:0,
            accyear:defaultDate4(), // 默认当年
            startDate:CurrentMonth(new Date(),'yyyy-MM'), // 开始日期
            endDate:dateFormat(new Date(),'yyyy-MM'), // 结束日期
        };
        this.onLoad(this.page);
      },
      searchChange(params, done) {
        this.query = params;
        this.page.currentPage = 1;
        this.onLoad(this.page, params);
        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 = {}) {
        if (this.query.startDate.split('-')[0] != this.query.endDate.split('-')[0]) {
            return this.$message.warning('开始日期和结束日期请选择同一年')
        }
        this.loading = true;
        fingenlegList(page.currentPage, page.pageSize, {
            ...Object.assign(params, this.query),
            startDate:Number(this.query.startDate.split('-')[1]),
            endDate:Number(this.query.endDate.split('-')[1]),
        }).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records.map(item=>{
              item.children = item.finGenlegs.map((ite,inde)=>{
                  ite.id = Number(inde) + 1
                  return ite
              })
              return item
          })
          this.loading = false;
          this.selectionClear();
        });
      },
        //自定义列保存
        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;
}
</style>
