<template>
  <basic-container>
    <avue-crud :option="option"
               :table-loading="loading"
               :data="data"
               :page.sync="page"
               :permission="permissionList"
               :before-open="beforeOpen"
               v-model="form"
               ref="crud"
               id="out-table"
               :header-cell-class-name="headerClassName"
               @resetColumn="resetColumnTwo('crud', 'option', 'optionBack', 311)"
               @saveColumn="saveColumnTwo('crud', 'option', 'optionBack', 311)"
               @row-update="rowUpdate"
               @row-save="rowSave"
               @rowAdd="addedData"
               @row-del="rowDel"
               @search-change="searchChange"
               @search-reset="searchReset"
               @selection-change="selectionChange"
               @current-change="currentChange"
               @size-change="sizeChange"
               @refresh-change="refreshChange"
               @on-load="onLoad">

      <template slot="cnName" slot-scope="scope">
        <avue-text-ellipsis :text="scope.row.cnName" :height="30" use-tooltip placement="top">
          <small slot="more">...</small>
        </avue-text-ellipsis>
      </template>
      <template slot="enName" slot-scope="scope">
        <avue-text-ellipsis :text="scope.row.enName" :height="30" use-tooltip placement="top">
          <small slot="more">...</small>
        </avue-text-ellipsis>
      </template>
      <template slot="remarks" slot-scope="scope">
        <avue-text-ellipsis :text="scope.row.remarks" :height="30" use-tooltip placement="top">
          <small slot="more">...</small>
        </avue-text-ellipsis>
      </template>
      <template slot="menuLeft">
        <el-button type="primary"
                   size="small"
                   icon="el-icon-plus"
                   @click="addedData(1)">新 建
        </el-button>
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   v-if="permission.businessbillno_delete"
                   @click="handleDelete">删 除
        </el-button>
      </template>
      <template slot-scope="{type,disabled}" slot="businessTypeIdForm">
        <el-select v-model="form.businessTypeId" clearable @change="businessTypeChange(form.businessTypeId)" placeholder="请选择">
          <el-option
            v-for="item in feesTypeList"
            :key="item.id"
            :label="item.cnName"
            :value="item.id">
          </el-option>
        </el-select>
      </template>
      <template slot-scope="scope" slot="menu">
        <el-link type="primary" style="font-size: 12px" icon="el-icon-view" :underline="false" @click="detail(scope.row.id)">查看详情&nbsp;&nbsp;</el-link>
        <el-link type="primary" style="font-size: 12px" icon="el-icon-edit" :underline="false" @click="addedData(2, scope)">编 辑&nbsp;&nbsp;</el-link>
        <el-link type="primary" style="font-size: 12px" icon="el-icon-delete" :underline="false" @click="rowDel(scope.row)">删 除</el-link>
      </template>
    </avue-crud>

    <el-dialog
      title="详情"
      :visible.sync="dialogVisible"
      :append-to-body="true"
      width="60%">
      <el-table :data="tableData" style="width: 100%" border
                :header-cell-style="{ background: '#ecf5ff', color: '#232526', fontSize: '12px' }" stripe>
        <el-table-column prop="resetValue" label="重置值"/>
        <el-table-column prop="serialNo" label="当前最大序列号"/>
        <el-table-column prop="status" label="状态">
          <template slot-scope="scope">
            <p v-if="scope.row.status == 0">正常</p>
            <p v-if="scope.row.status == 1">停用</p>
          </template>
        </el-table-column>
        <el-table-column prop="remarks" label="备注"/>
      </el-table>
<!--      <span slot="footer" class="dialog-footer">-->
<!--        <el-button @click="dialogVisible = false">取 消</el-button>-->
<!--        <el-button type="primary" @click="dialogVisible = false">确 定</el-button>-->
<!--      </span>-->
    </el-dialog>

  </basic-container>
</template>

<script>
  import {getList, getDetail, add, update, remove} from "@/api/los/businessbillno/businessbillno";
  import {mapGetters} from "vuex";

  import {bbusinesstypeList} from "@/api/iosBasicData/bbusinesstype";

  export default {
    data() {
      return {
        dialogVisible: false,
        tableData: [],
        form: {},
        query: {},
        feesTypeList: [],
        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,
          column: [
            {
              label: "业务类型",
              prop: "businessTypeId",
              width: "180",
              search:true,
              formslot: true,
              type: 'select',
              props: {
                label: 'cnName',
                value: 'id'
              },
              dicData: [],
              change: (column,value) => {
                // console.log(column)
                // if (column) {
                //     this.feesTypeList.forEach(data => {
                //       if (data.id == column.value) {
                //         this.form.businessType = data.code
                //       }
                //     })
                // }
              },
              rules: [{
                required: true,
                message: "请输入业务类型表 id",
                trigger: "blur"
              }]
            },
            {
              label: "业务类型代码",
              prop: "businessType",
              width: "100",
              readonly: true
            },
            {
              label: "单据号码格式代码",
              prop: "code",
              width: "120",
              rules: [{
                required: true,
                message: "请输入单据号码格式代码",
                trigger: "blur"
              }]
            },
            {
              label: "单据号码格式中文名称",
              prop: "cnName",
              width: "180",
              rules: [{
                required: true,
                message: "请输入单据号码格式名称",
                trigger: "blur"
              }]
            },
            {
              label: "单据号码格式英文名称",
              prop: "enName",
              width: "180",
              rules: [{
                required: true,
                message: "请输入单据号码格式名称",
                trigger: "blur"
              }]
            },
            {
              label: "单据号码格式，BL[Y4][M2][D2][N6]",
              prop: "codeFormat",
              width: "180",
              rules: [{
                required: true,
                message: "请输入单据号码格式，BL[Y4][M2][D2][N6]",
                trigger: "blur"
              }]
            },
            {
              label: "是否可回收",
              prop: "isRecyclable",
              width: "100",
              type: 'select',
              dicData:[{
                label:'否',
                value:0
              },{
                label:'是',
                value:1
              }],
              rules: [{
                required: true,
                message: "请输入是否可回收（0 否 1是）",
                trigger: "blur"
              }]
            },
            {
              label: "是否检测空号",
              prop: "isCheckEmpty",
              width: "100",
              type: 'select',
              dicData:[{
                label:'否',
                value:0
              },{
                label:'是',
                value:1
              }],
              rules: [{
                required: true,
                message: "请输入是否检测空号（0 否 1是）",
                trigger: "blur"
              }]
            },
            {
              label: "重置规则",
              prop: "resetRule",
              type: 'select',
              dicData:[{
                label:'年',
                value: 'Year'
              },{
                label:'月',
                value: 'Month'
              }]
            },
            {
              label: "状态",
              prop: "status",
              type: 'select',
              dicData:[{
                label:'正常',
                value:0
              },{
                label:'1停用',
                value:1
              }],
              rules: [{
                required: true,
                message: "请输入状态",
                trigger: "blur"
              }]
            },
            {
              label: "备注",
              prop: "remarks",
              width: "180",
            },
          ]
        },
        data: []
      };
    },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.businessbillno_add, false),
          viewBtn: this.vaildData(this.permission.businessbillno_view, false),
          delBtn: this.vaildData(this.permission.businessbillno_delete, false),
          editBtn: this.vaildData(this.permission.businessbillno_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(311), this.optionBack);
      bbusinesstypeList().then(res => {
        this.findObject(this.option.column, "businessTypeId").dicData = res.data.data.records
        this.feesTypeList = res.data.data.records
      })
    },
    methods: {
      businessTypeChange(column) {
        // console.log(column, 1234)
        if (column) {
          this.feesTypeList.forEach(data => {
            if (data.id == column) {
              this.form.businessType = data.code
            }
          })
        }
      },
      addedData(type, scope) {
        this.form = {};
        if (type == 1) {
          this.$refs.crud.rowAdd();
        } else if (type == 2) {
          this.$refs.crud.rowEdit(scope.row, scope.$index);
        }
      },
      rowSave(row, done, loading) {
        add(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        update(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 remove(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 remove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          getDetail(this.form.id).then(res => {
            this.form = res.data.data;
          });
        }
        done();
      },
      detail(id) {
          getDetail(id).then(res => {
            this.tableData = res.data.data.billNoSerialList
            this.dialogVisible = true;
          });
      },
      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;
        getList(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();
        });
      },
      //自定义列保存
      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 lang="scss" scoped>
::v-deep#out-table .back-one {
  background: #ecf5ff !important;
}

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

::v-deep .el-input-group__append {
  padding: 0 0px !important;
}

/deep/ .el-tree-node__content>.el-tree-node__expand-icon {
  visibility: hidden;
}

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