<template>
  <div>
    <basic-container v-show="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', 322)"
        @saveColumn="saveColumnTwo('crud', 'option', 'optionBack', 322)" @on-load="onLoad">
        <template slot="menuLeft">
          <el-button type="primary" size="small" icon="el-icon-plus" @click="addbtnfun()">新建AMEND
          </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" icon="el-icon-edit" @click.stop="rowEdit(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 == 2 || row.status == 3" @click.stop="rowDel(row)"
            icon="el-icon-delete">删除
          </el-button>
        </template>
        <template slot="billNo" slot-scope="{ row }">
          <span style="color: #1e9fff;cursor: pointer;" @click="rowEdit(row)">{{ row.billNo }}
          </span>
        </template>
      </avue-crud>
    </basic-container>
    <amends-details ref="amendsDetails" v-if="!isShow" @goBack="goBack"></amends-details>
  </div>
</template>

<script>
import { amendsList, amendsDetail, amendsSubmit, amendsRemove } from "@/api/iosBasicData/amends";
import amendsDetails from "@/views/iosBasicData/siamends/amendsDetails.vue";
import { mapGetters } from "vuex";
import { getWorkDicts } from "@/api/system/dictbiz";
import { getBcorpslistByType } from "@/api/iosBasicData/bcorps";

export default {
  components: { amendsDetails },
  data() {
    return {
      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: '140',
        searchIcon: true,
        searchIndex: 3,
        column: [
          {
            label: "客户名称",
            prop: "corpCnName",
            search: true,
            overHidden: true,
            type: 'select',
            filterable: true,
            remote: true,
            dicUrl: "/api/blade-los/bcorps/listByType?shortName={{key}}",
            dicData: [],
            props: {
              label: 'cnName',
              value: 'cnName',
              res: 'data.records'
            },
          },
          {
            label: "单据编号",
            prop: "billNo",
            search: true,
            overHidden: true,
          },
          {
            label: "所属团队",
            prop: "teamName",
            overHidden: true,
          },
          {
            label: "原MB/L NO",
            prop: "mblno",
            search: true,
            overHidden: true,
          },
          {
            label: "原HB/L NO",
            prop: "hblno",
            search: true,
            overHidden: true,
          },
          {
            label: "BOOKING NO",
            prop: "bookingNo",
            searchLabelWidth: 100,
            search: true,
            overHidden: true,
          },
          {
            label: "原船名",
            prop: "vesselCnName",
            overHidden: true,
          },
          {
            label: "原航次",
            prop: "voyageNo",
            overHidden: true,
          },
          {
            label: "原外提单号",
            prop: "refno",
            search: true,
            overHidden: true,
          },
          {
            label: "单据日期",
            prop: "billDate",
            overHidden: true,
          },
          {
            label: "原单据编号",
            prop: "origBillNo",
            search: true,
            overHidden: true,
          },
          {
            label: "单据类型",
            prop: "origBillType",
            overHidden: true,
            rules: [{
              required: true,
              message: "请输入单据类型, DD=直单(默认) MM=主单 MH=主分单 HH=从分单",
              trigger: "blur"
            }]
          },
          {
            label: "状态",
            prop: "status",
            search: true,
            type: "select",
            dicUrl: "/api/blade-system/dict-biz/dictionary?code=ameno_status",
            dicData: [],
            props: {
              label: "dictValue",
              value: "dictKey"
            },
            overHidden: true,
          },
          {
            label: "单据开始日期",
            prop: "billDateStart",
            search: true,
            overHidden: true,
            hide: true,
            searchLabelWidth: '100',
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
          },
          {
            label: "单据结束日期",
            prop: "billDateEnd",
            search: true,
            overHidden: true,
            hide: true,
            searchLabelWidth: '100',
            type: "date",
            format: "yyyy-MM-dd",
            valueFormat: "yyyy-MM-dd HH:mm:ss",
          },
          {
            label: "备注",
            prop: "remarks",
            overHidden: true,
          },
        ]
      },
      data: [],
      saberUserInfo: {}, // 当前登录人个人信息
    };
  },
  computed: {
    ...mapGetters(["permission"]),
    permissionList() {
      return {
        addBtn: this.vaildData(this.permission.amends_add, false),
        viewBtn: this.vaildData(this.permission.amends_view, false),
        delBtn: this.vaildData(this.permission.amends_delete, false),
        editBtn: this.vaildData(this.permission.amends_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(322), this.optionBack);
    // 首页快捷跳转进来的
    if (this.$route.query.home) {
      this.addbtnfun()
    }
    if (this.$route.query.billId) {
      // 从审批里查看跳进来的
      this.rowEdit({ id: this.$route.query.billId })
    }
    this.$store.commit('SIA_IN_DETAIL')
    this.getWorkDictsfun()
  },
  activated() {
    if (this.$route.query.id) {
      if (!this.$store.getters.OFIStatus) {
        setTimeout(() => {
          this.rowEdit(this.$route.query)
        }, 200);
      }
    }
  },
  methods: {
    getWorkDictsfun() {
      getBcorpslistByType(1, 10).then(res => {
        this.findObject(this.option.column, "corpCnName").dicData = res.data.data.records
      })
      // 状态
      getWorkDicts('ameno_status').then(res => {
        this.findObject(this.option.column, "status").dicData = res.data.data
      })
    },
    // 新建amend
    addbtnfun() {
      this.isShow = false
      this.$store.commit("IN_OFI_DETAIL");
    },
    // 编辑
    rowEdit(row) {
      this.isShow = false
      this.$nextTick(() => {
        this.$refs.amendsDetails.amendsDetailfun(row.id)
      })
      this.$store.commit("IN_OFI_DETAIL");
    },
    // 详情的返回列表
    goBack() {
      // 初始化数据
      if (JSON.stringify(this.$route.query) != "{}") {
        this.$router.$avueRouter.closeTag();
        this.$router.push({
          path: "/iosBasicData/siamends/index"
        });
      }
      this.isShow = true;
      this.onLoad(this.page, this.search);
      this.$store.commit("OUT_OFI_DETAIL");
    },
    rowSave(row, done, loading) {
      amendsSubmit(row).then(() => {
        this.onLoad(this.page);
        this.$message({
          type: "success",
          message: "操作成功!"
        });
        done();
      }, error => {
        loading();
        window.console.log(error);
      });
    },
    rowUpdate(row, index, done, loading) {
      amendsSubmit(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 amendsRemove(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;
      for (let item of this.selectionList) {
        if (item.status == 1 || item.status == 2 || item.status == 3) {
          return this.$message.warning('请选择还未请核的数据')
        }
      }
      this.$confirm("确定将选择数据删除?", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      })
        .then(() => {
          return amendsRemove(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)) {
        amendsDetail(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;
      amendsList(page.currentPage, page.pageSize, { ...Object.assign(params, this.query), businessType: 'SIA' }).then(res => {
        const data = res.data.data;
        this.page.total = data.total;
        this.data = data.records.map(item => {
          item.status = item.status + ''
          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;
}

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