<template>
  <div>
      <basic-container v-if="isShow">
          <avue-crud :option="option"
                     :table-loading="loading"
                     :data="data"
                     :page.sync="page"
                     :permission="permissionList"
                     :before-open="beforeOpen"
                     v-model="form"
                     id="out-table"
                     :header-cell-class-name="headerClassName"
                     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"
                     @resetColumn="resetColumnTwo('crud', 'option', 'optionBack', 323)"
                     @saveColumn="saveColumnTwo('crud', 'option', 'optionBack', 323)"
                     @on-load="onLoad"
                     @tree-load="treeLoad" >
              <template slot="menuLeft">
                  <el-button type="primary"
                             size="small"
                             icon="el-icon-plus"
                             @click="addAccountsfun">新 增
                  </el-button>
                  <el-button type="danger"
                             size="small"
                             icon="el-icon-delete"
                             plain
                             @click="handleDelete">删 除
                  </el-button>
                  <div style="margin-top: 10px">
                      <el-tabs type="card" v-model="query.property" @tab-click="handleClick">
                          <el-tab-pane :label="item.dictValue" :name="item.dictKey"
                                       v-for="item in propertyData" :key="item.dictKey">
                              <span slot="label">{{item.dictValue}}</span>
                          </el-tab-pane>
                      </el-tabs>
                  </div>
              </template>
              <template slot="menu" slot-scope="{ row, index }">
                  <el-button size="small" icon="el-icon-edit" type="text" @click="editfun(row,index)">编辑</el-button>
                  <!--<el-button v-if="row.isItem == 1" size="small" type="text" @click="editOpeningfun(row,index)">核算期初</el-button>-->
                  <el-button size="small" type="text" @click="addChildfun(row,index)">添加子项</el-button>
                  <el-button size="small" icon="el-icon-delete" type="text" @click="rowDel(row, index)">删 除</el-button>
              </template>
              <template slot="code" slot-scope="{ row }">
                  <span style="color: #1e9fff" @click="editDetailsfun(row.id)">{{row.code}}</span>
              </template>
              <template slot="isItem" slot-scope="{ row }">
                  <span class="pointerClick" v-if="row.isItem == 1" @click="editOpeningfun(row)" >是</span>
                  <span v-else >否</span>
              </template>
              <template slot="quantityOpenDr" slot-scope="{ row }">
                  <el-input style="width: 100%;" v-model="row.quantityOpenDr"
                            v-if="row.edit" type="number" min="0"
                            size="mini" autocomplete="off" clearable
                            placeholder="请输入期初借方数量" >
                  </el-input>
                  <span v-else >{{row.quantityOpenDr}}</span>
              </template>



          </avue-crud>
      </basic-container>

      <!--辅助核算-->
      <el-dialog
          title="账户管理"
          append-to-body
          :visible.sync="accountsVisible"
          class="el-dialogDeep"
          width="60%"
          :before-close="handleClose">
          <accounts-dialog ref="accountsDialog" :form="form"></accounts-dialog>
          <span slot="footer" class="dialog-footer">
                <el-button @click="accountsVisible = false">取 消</el-button>
                <el-button type="primary" @click="bigSavefun">确 定</el-button>
            </span>
      </el-dialog>

      <!--从表数据-->
      <el-dialog
          title="辅助核算期初"
          append-to-body
          :visible.sync="sopenblcVisible"
          class="el-dialogDeep"
          width="70%"
          :before-close="handleClose">
          <accitemsopenblc :form="form" ></accitemsopenblc>
          <span slot="footer" class="dialog-footer">
                <el-button @click="sopenblcVisible = false">取 消</el-button>
                <el-button type="primary" @click="openingCalculatefun">保 存</el-button>
          </span>
      </el-dialog>

      <!--<accountsDetails v-if="!isShow" @goBack="goBack"></accountsDetails>-->
  </div>
</template>

<script>
  import {accountsList, accountsDetail, accountsSubmit, accountsRemove} from "@/api/iosBasicData/accounts";
  import {mapGetters} from "vuex";
  import accountsDialog from "@/views/iosBasicData/accounts/assembly/accountsDialog.vue";
  import accountsDetails from "@/views/iosBasicData/accounts/accountsDetails.vue";
  import {getWorkDicts} from "@/api/system/dictbiz";
  import accitemsopenblc from "@/views/iosBasicData/accounts/assembly/accitemsopenblc.vue";

  export default {
    data() {
      return {
        accountsVisible:false, // 添加编辑弹窗
        sopenblcVisible:false, // 从表数据
        isShow:true,
        form: {},
        query: {
            property:'0',
        },
        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:"200",
          lazy: true,
          tree: true,
          rowKey:'code',
          rowParentKey:'children',
          simplePage: true,
          searchIcon:true,
          searchIndex:2,
          column: [
            {
              label: "科目代码",
              prop: "code",
              search: true,
              width: "80",
              overHidden: true,
            },
            {
              label: "中文名称",
              prop: "cnName",
              search: true,
              width: "80",
              overHidden: true,
            },
            {
              label: "方向",
              prop: "dc",
              overHidden: true,
              type:'select',
              search: true,
                width: "50",
              dicData:[
                  {
                      label:'借方',
                      value:'D',
                  },
                  {
                      label:'贷方',
                      value:'C',
                  }
              ]
            },
            {
              label: "外币",
              prop: "isForeign",
              overHidden: true,
              search: true,
              type:'select',
                width: "35",
              dicData:[
                  {
                      label:'否',
                      value:0,
                  },
                  {
                      label:'是',
                      value:1,
                  }
              ]
            },
            {
              label: "币种",
              prop: "curCode",
              overHidden: true,
              search: true,
                width: "50",
            },
            {
              label: "数量",
              prop: "isQuantity",
              overHidden: true,
              search: true,
              type:'select',
                width: "35",
              dicData:[
                  {
                      label:'否',
                      value:0,
                  },
                  {
                      label:'是',
                      value:1,
                  }
              ]
            },
            {
              label: "客户",
              prop: "isCorp",
              overHidden: true,
              search: true,
              type:'select',
                width: "35",
              dicData:[
                  {
                      label:'否',
                      value:0,
                  },
                  {
                      label:'是',
                      value:1,
                  }
              ]
            },
            {
              label: "部门",
              prop: "isDept",
              overHidden: true,
              search: true,
              type:'select',
                width: "35",
              dicData:[
                  {
                      label:'否',
                      value:0,
                  },
                  {
                      label:'是',
                      value:1,
                  }
              ]
            },
            {
              label: "职员",
              prop: "isEmpl",
              overHidden: true,
              search: true,
              type:'select',
                width: "35",
              dicData:[
                  {
                      label:'否',
                      value:0,
                  },
                  {
                      label:'是',
                      value:1,
                  }
              ]
            },
            {
              label: "项目",
              prop: "isItem",
              overHidden: true,
              search: true,
              type:'select',
                width: "35",
              dicData:[
                  {
                      label:'否',
                      value:0,
                  },
                  {
                      label:'是',
                      value:1,
                  }
              ]
            },
            {
                label: "上级科目",
                prop: "parentCode",
                overHidden: true,
            },
              // {
              //     label: "children",
              //     prop: "children",
              //     hasChildren:true,
              // },
            {
                label: "期初数量借方",
                prop: "quantityOpenDr",
                overHidden: true,
            },
            {
              label: "期初本币借方金额",
              prop: "amountOpenDr",
              overHidden: true,
            },
            {
              label: "期初外币借方金额",
              prop: "amountOpenDrUsd",
              overHidden: true,
            },
            {
                label: "期初数量贷方",
                prop: "quantityOpenCr",
                overHidden: true,
            },
            {
              label: "期初本币贷方金额",
              prop: "amountOpenCr",
              overHidden: true,
            },
            {
              label: "期初外币贷方金额",
              prop: "amountOpenCrUsd",
              overHidden: true,
            },
            {
                label: "期初数量余额",
                prop: "quantityOpenUsdBlc",
                overHidden: true,
            },
            {
              label: "期初本币余额",
              prop: "amountOpenBlc",
              overHidden: true,
            },
            {
                label: "期初外币余额",
                prop: "amountOpenUsdBlc",
                overHidden: true,
            },
            {
                label: "本期数量借方",
                prop: "quantityDr",
                overHidden: true,
            },
            {
              label: "本期本币借方金额",
              prop: "amountDr",
              overHidden: true,
            },
            {
                label: "本期外币借方金额",
                prop: "amountDrUsd",
                overHidden: true,
            },
            {
                label: "本期数量贷方",
                prop: "quantityCr",
                overHidden: true,
            },
            {
              label: "本期本币贷方金额",
              prop: "amountCr",
              overHidden: true,
            },
            {
                label: "本期外币贷方金额",
                prop: "amountCrUsd",
                overHidden: true,
            },
            {
                label: "本期数量余额",
                prop: "quantityUsdBlc",
                overHidden: true,
            },
            {
              label: "本期本币余额",
              prop: "amountBlc",
              overHidden: true,
            },
            {
              label: "本期外币余额",
              prop: "amountUsdBlc",
              overHidden: true,
            },
            {
              label: "备注",
              prop: "remarks",
              overHidden: true,
            },
          ]
        },
        data: [],
        propertyData:[], // 科目类别
      };
    },
    components:{accitemsopenblc, accountsDialog,accountsDetails},
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.accounts_add, false),
          viewBtn: this.vaildData(this.permission.accounts_view, false),
          delBtn: this.vaildData(this.permission.accounts_delete, false),
          editBtn: this.vaildData(this.permission.accounts_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(323), this.optionBack);
        this.propertyWorkDictsfun()
    },
    methods: {
        // 辅助核算期初确认
        openingCalculatefun(){
            this.accountsSubmitfun()
            this.sopenblcVisible = false
        },
        // 核算项目数据
        propertyWorkDictsfun(cnName){
            getWorkDicts('itemClassify_los').then((res) => {
                this.propertyData = res.data.data
            });
        },
        // 添加
      addAccountsfun(){
          this.form = {}
          this.accountsVisible = true
          // this.isShow = false
      },
        // 编辑
        editDetailsfun(id){
            // 详情接口
            accountsDetail(id).then(res => {
                this.form = res.data.data;
                this.$set(this.form,'property',this.form.property + '')
            });
            this.accountsVisible = true
        },
        // 大保存
        bigSavefun(){
            let sum = '请填写'
            if (!this.form.code) {
                sum += '科目编码 '
            }
            if (!this.form.cnName) {
                sum += '科目名称 '
            }
            if (!this.form.dc) {
                sum += '方向 '
            }
            if (sum != '请填写') {
                this.$alert(sum, '提示', {
                    confirmButtonText: '确定',
                });
                return
            }
            this.accountsSubmitfun()
        },
        // 保存
        accountsSubmitfun(){
            accountsSubmit(this.form).then(res=>{
                this.$message.success("操作成功!")
                this.accountsVisible = false
                this.onLoad(this.page, this.query)
            })
        },
      // 弹窗点击差号
      handleClose(done) {
          this.$confirm('确认关闭？')
              .then(_ => {
                  done();
              })
              .catch(_ => {});
      },
        // 添加
      rowSave(row, done, loading) {
        accountsSubmit(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
        // 编辑操作
      rowUpdate(row, index, done, loading) {
        accountsSubmit(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
        });
      },
        // 删除
      rowDel(row) {
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return accountsRemove(row.id);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
          });
      },
        // 编辑
        editfun(row){
            accountsDetail(row.id).then(res => {
                this.form = res.data.data;
                this.$set(this.form,'property',this.form.property + '')
            });
            this.accountsVisible = true
            this.$nextTick(()=>{
                this.$refs.accountsDialog.propertyWorkDictsfun()
            })
        },
        // 添加子项
        addChildfun(row){
            this.form = {
                parentId:row.id,
                parentCode:row.code,
                parentCnName:row.cnName,
            }
            this.accountsVisible = true
        },
        // 核算期初
        editOpeningfun(row){
            accountsDetail(row.id).then(res => {
                this.form = res.data.data;
            });
            this.sopenblcVisible = true
        },

        // 匹配删除
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return accountsRemove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
        // 打开弹窗调用详情接口
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          accountsDetail(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, 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 = {}) {
        this.loading = true;
        accountsList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
          const data = res.data.data;
          this.page.total = data.total;
          this.data = data.records;
          this.loading = false;
          this.selectionClear();
        });
      },
      // 懒加载查询子节点数据
      treeLoad(row, treeNode, resolve){
          console.log(row,688)
          console.log(row,treeNode,resolve,673)
      },
      // 详情的返回列表
      goBack() {
          // 初始化数据
          if (JSON.stringify(this.$route.query) != "{}") {
              this.$router.$avueRouter.closeTag();
              this.$router.push({
                  path: "/iosBasicData/accounts/index"
              });
          }
          this.isShow = true;
          this.onLoad(this.page, this.search);
      },
      //自定义列保存
      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;
}
.pointerClick {
    cursor:pointer;
    color: #1e9fff;
}
</style>
