<!-- 货物 -->
<template>
  <basic-container>
    <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"
               @resetColumn="resetColumnTwo('crud', 'option', 'optionBack', 290)"
               @saveColumn="saveColumnTwo('crud', 'option', 'optionBack', 290)"
               @on-load="onLoad">
      <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="addbtnfun()">新建包装
          </el-button>
        <el-button type="danger"
                   size="small"
                   icon="el-icon-delete"
                   plain
                   @click="handleDelete">删 除
        </el-button>
      </template>

        <template slot="unitNoForm">
            <search-query ref="SearchQuery"
                          :datalist="unitNoData"
                          title="计量单位"
                          :filterable="true"
                          :clearable="true"
                          :remote="true"
                          :forParameter="{key:'id',label:'cnName',value:'cnName'}"
                          @remoteMethod="getBunitsListfun" @corpChange="corpChange" >
                <bunits @selectionChange="selectionBunits"></bunits>
            </search-query>
        </template>

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

<script>
  import {bcommodityList, bcommodityDetail, bcommoditySubmit, bcommodityRemove} from "@/api/iosBasicData/bcommodity";
  import {mapGetters} from "vuex";
  import SearchQuery from '@/components/iosbasic-data/searchquery.vue'
  import bunits from '@/views/iosBasicData/bunits/index.vue'
  import {getBunitsList} from "@/api/iosBasicData/bunits";

  export default {
    data() {
      return {
          // 计算单位请求到的数据
          unitNoData:[],
        form: {},
        query: {},
        loading: true,
        page: {
          pageSize: 10,
          currentPage: 1,
          total: 0
        },
        selectionList: [],
        option:{},
        optionBack: {
            addBtnText:'新建货物',
            addTitle:'新建货物',
            editBtnText:'编辑',
            editTitle:'编辑货物',
            viewBtnText:'查看',
            viewTitle:'查看货物',
          height:'auto',
          stripe: true,
          calcHeight: 30,
            labelWidth:100,
          tip: false,
          searchShow: true,
          searchMenuSpan: 6,
          border: true,
          index: true,
          viewBtn: true,
          selection: true,
          dialogClickModal: false,
          column: [
            {
              label: "HS CODE",
              prop: "hsCode",
                search: true,
              rules: [{
                required: true,
                message: "请输入HS CODE(The Harmonization System Code)",
                trigger: "blur"
              }]
            },
            {
              label: "中文名称",
              prop: "cnName",
                search: true,
              rules: [{
                required: true,
                message: "请输入中文名称",
                trigger: "blur"
              }]
            },
            {
              label: "英文名称",
              prop: "enName",
                search: true,
              rules: [{
                required: true,
                message: "请输入英文名称",
                trigger: "blur"
              }]
            },
            {
              label: "计量单位",
              prop: "unitNo",
                formslot:true,
                type:'select',
                clearable:false,
                dicData:[],
              // rules: [{
              //   required: true,
              //   message: "请输入计量单位",
              //   trigger: "blur"
              // }]
            },
            {
              label: "NCM CODE",
              prop: "ncmCode",
                width:100,
            },
            {
              label: "版本",
              prop: "version",
                hide:true,
                display:false,
            },
            {
              label: "状态",
              prop: "status",
                type:'select',
                dicData:[{
                    label:'正常',
                    value:0
                },{
                    label:'停用',
                    value:1
                }],
            },
            {
              label: "是否已删除（0 否 1是）",
              prop: "isDeleted",
                hide:true,
                display:false,
            },
              {
                  label: "主键",
                  prop: "id",
                  hide:true,
                  display:false,
              },
              {
                  label: "创建人 Id",
                  prop: "createUser",
                  hide:true,
                  display:false,
              },
              {
                  label: "创建人",
                  prop: "createUserName",
                  display:false,
              },
              {
                  label: "创建部门 Id",
                  prop: "createDept",
                  hide:true,
                  display:false,
              },
              {
                  label: "创建部门",
                  prop: "createDeptName",
                  display:false,
              },
              {
                  label: "创建时间",
                  prop: "createTime",
                  width: 160,
                  display:false,
              },
              {
                  label: "修改人 Id",
                  prop: "updateUser",
                  hide:true,
                  display:false,
              },
              {
                  label: "修改人",
                  prop: "updateUserName",
                  display:false,
              },
              {
                  label: "修改时间",
                  prop: "updateTime",
                  display:false,
              },
            {
              label: "备注",
              prop: "remarks",
                type: 'textarea',
                width: "180",
                slot: true,
                span: 24,
                minRows: 3,
            },
          ]
        },
        data: []
      };
    },
      components:{
          SearchQuery,
          bunits
      },
    computed: {
      ...mapGetters(["permission"]),
      permissionList() {
        return {
          addBtn: this.vaildData(this.permission.bcommodity_add, false),
          // viewBtn: this.vaildData(this.permission.bcommodity_view, false),
          // delBtn: this.vaildData(this.permission.bcommodity_delete, false),
          // editBtn: this.vaildData(this.permission.bcommodity_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(290), this.optionBack);
        // 获取计算单位数据
        this.getBunitsListfun()
    },
    methods: {
        // 获取计算单位数据
        getBunitsListfun(cnName){
            getBunitsList(1, 10,{cnName}).then(res=>{
                this.unitNoData = res.data.data.records
            })
        },
        // 计量单位选中的回调
        corpChange(value){
            this.form.unitNo = value
            // for(let item of this.unitNoData) {
            //     if (item.id == value) {
            //         this.form.unitNo = item.cnName
            //     }
            // }
        },
        // 新增
        addbtnfun(){
            this.form.status = 0
            this.$refs.crud.rowAdd()
        },
        // 表格组件抛出的选择数据
        selectionBunits(list){
            console.log(list,271)
        },
      rowSave(row, done, loading) {
        bcommoditySubmit(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          window.console.log(error);
        });
      },
      rowUpdate(row, index, done, loading) {
        bcommoditySubmit(row).then(() => {
          this.onLoad(this.page);
          this.$message({
            type: "success",
            message: "操作成功!"
          });
          done();
        }, error => {
          loading();
          console.log(error);
        });
      },
      rowDel(row) {
          if (row.status === 1) {
              this.$confirm("确定将选择数据删除?", {
                  confirmButtonText: "确定",
                  cancelButtonText: "取消",
                  type: "warning"
              })
                  .then(() => {
                      return bcommodityRemove(row.id);
                  })
                  .then(() => {
                      this.onLoad(this.page);
                      this.$message({
                          type: "success",
                          message: "操作成功!"
                      });
                  });
          }else {
              this.$message({
                  message: '非禁用状态无法删除',
                  type: 'warning'
              });
          }
      },
      handleDelete() {
        if (this.selectionList.length === 0) {
          this.$message.warning("请选择至少一条数据");
          return;
        }
        this.$confirm("确定将选择数据删除?", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        })
          .then(() => {
            return bcommodityRemove(this.ids);
          })
          .then(() => {
            this.onLoad(this.page);
            this.$message({
              type: "success",
              message: "操作成功!"
            });
            this.$refs.crud.toggleSelection();
          });
      },
      beforeOpen(done, type) {
        if (["edit", "view"].includes(type)) {
          bcommodityDetail(this.form.id).then(res => {
            this.form = res.data.data;
            // 获取插槽数据
            this.$nextTick(()=>{
               console.log(this.$refs.SearchQuery.selectValue)
               this.$refs.SearchQuery.selectValue = this.form.unitNo
            })
          });
        }
        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;
        bcommodityList(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;
    }

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

</style>
