<template>
  <div class="detail-container">
    <el-page-header @back="goBack" :content="listItem ? '编辑':'新增'"></el-page-header>

    <div class="main-title">
      <div class="title">预留单信息</div>
    </div>

    <el-form ref="mainForm" :model="mainForm" label-width="70px" size="small" label-position="left">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :lg="6">
          <el-form-item label="单据编号" prop="orderNum">
            <el-input v-model="mainForm.orderNum" placeholder="系统自动生成" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="6" style="height: 51px;">
          <el-form-item label="单据日期" prop="orderDate">
            <el-date-picker
              v-model="mainForm.orderDate"
              type="date"
              value-format="yyyy-MM-dd"
              style="width: 100%;"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="6">
          <el-form-item label="制单人" prop="createMan">
            <el-input v-model="mainForm.createMan" placeholder="请输入制单人" readonly></el-input>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :lg="6" style="height: 51px;">
          <el-form-item label="制单日期" prop="createDate">
            <el-date-picker
              v-model="mainForm.createDate"
              readonly
              type="datetime"
              value-format="yyyy-MM-dd HH:mm:ss"
              style="width: 100%;"
              placeholder="选择日期">
            </el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="24" :lg="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="mainForm.remark" placeholder="请输入备注"></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <div style="margin-top: 20px">
      <el-button type="primary" size="small" icon="el-icon-plus" @click="openDialog">添加引用</el-button>
      <el-button type="danger" size="small" icon="el-icon-minus" @click="deleteGoods" :disabled="tableSelection.length < 1">批量删除</el-button>
    </div>
    <div class="table" style="margin-top: 20px">
      <el-table :data="goodsList" element-loading-text="Loading" border fit highlight-current-row stripe max-height="400" @selection-change="tableSelectionChange">
        <el-table-column align="center" type="selection" width="55"></el-table-column>
        <el-table-column align="center" label="销售订单号" prop="orderId" min-width="180" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="订单日期" prop="orderDate" min-width="120" show-overflow-tooltip>
          <template slot-scope="scope">
            {{scope.row.orderDate | dateToDayFilter}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="经销商编码" prop="customerId" min-width="120" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="经销商名称" prop="customerName" min-width="160" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="物料代码" prop="materialOldNumber" min-width="160" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="产品编码" prop="materialCode" min-width="160" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="产品名称" prop="materialName" min-width="160" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="规格型号" prop="specification" min-width="100" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="单位" prop="unit" min-width="100" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="预留数量" prop="reservedNum" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            <el-input v-model="scope.row.reservedNum" size="small"></el-input>
          </template>
        </el-table-column>
        <el-table-column align="center" label="订单数量" prop="qty" min-width="100" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="备注" prop="reservedRemark" min-width="160" show-overflow-tooltip></el-table-column>
        <el-table-column align="center" label="状态" prop="status" min-width="100" show-overflow-tooltip>
          <template slot-scope="scope">
            {{scope.row.status ? '执行中':'已关闭'}}
          </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="100" fixed="right">
          <template slot-scope="scope">
            <el-button type="text" @click="deleteItem(scope.$index)" v-if="!listItem">删除</el-button>

            <el-button type="text" @click="changeItem(scope.$index, 0)" v-if="listItem && scope.row.status === 1">关闭</el-button>
            <el-button type="text" @click="changeItem(scope.$index, 1)" v-if="listItem && scope.row.status === 0">开启</el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    
    <div class="page-footer">
      <div class="footer" :class="classObj">
        <el-button type="primary" @click="clickSubmitForm">保 存</el-button>
        <el-popconfirm title="确定关闭吗？" @onConfirm="goBack" style="margin-left: 10px;">
          <el-button slot="reference">关 闭</el-button>
        </el-popconfirm>
      </div>
    </div>

    <el-dialog title="添加引用" :visible.sync="isShowDialog" width="80%">
      <el-form ref="screenForm" :model="screenForm" size="small" label-position="left">
        <el-row :gutter="20">
          <el-col :xs="12" :sm="6" :lg="4">
            <el-form-item prop="jxsNum">
              <el-input v-model="screenForm.jxsNum" placeholder="经销商编码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="4">
            <el-form-item prop="jxsName">
              <el-input v-model="screenForm.jxsName" placeholder="经销商名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="4">
            <el-form-item prop="type">
              <el-select v-model="screenForm.type" placeholder="产品大类" style="width: 100%">
                <el-option v-for="item in typeList" :key="item.dictValue" :label="item.dictValue" :value="item.dictValue"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="4">
            <el-form-item prop="goodsNum">
              <el-input v-model="screenForm.goodsNum" placeholder="产品编码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="4">
            <el-form-item prop="goodsCode">
              <el-input v-model="screenForm.goodsCode" placeholder="物料代码"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="4">
            <el-form-item prop="goodsName">
              <el-input v-model="screenForm.goodsName" placeholder="产品名称"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="4">
            <el-form-item prop="model">
              <el-input v-model="screenForm.model" placeholder="规格型号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="4">
            <el-form-item prop="orderType">
              <el-select v-model="screenForm.orderType" placeholder="订单类型" style="width: 100%">
                <el-option v-for="item in orderTypeList" :key="item.value" :label="item.label" :value="item.value"></el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="6" :lg="4">
            <el-form-item prop="saleNum">
              <el-input v-model="screenForm.saleNum" placeholder="销售订单号"></el-input>
            </el-form-item>
          </el-col>
          <el-col :xs="12" :sm="18" :lg="12" class="tr">
            <el-form-item label="">
              <el-button size="small" @click="resetScreenForm">清空</el-button>
              <el-button size="small" type="primary" @click="submitScreenForm">搜索</el-button>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>

      <div class="table">
        <el-table :data="dialogGoodsList" element-loading-text="Loading" border fit highlight-current-row stripe height="400" @selection-change="dialogSelectionChange">
          <el-table-column align="center" type="selection" width="55" :selectable='checkboxSelect'></el-table-column>
          <el-table-column align="center" label="经销商编码" prop="customerNumber" min-width="120" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="经销商名称" prop="customerName" min-width="160" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="订单日期" prop="orderTime" min-width="120" show-overflow-tooltip>
            <template slot-scope="scope">
              {{scope.row.orderTime | dateToDayFilter}}
            </template>
          </el-table-column>
          <el-table-column align="center" label="订单类型" prop="orderType" min-width="100" show-overflow-tooltip>
            <template slot-scope="scope">
              {{scope.row.orderType | orderTypeFilter}}
            </template>
          </el-table-column>
          <el-table-column align="center" label="订单号" prop="orderId" min-width="180" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="销售类型" prop="saleTypeName" min-width="100" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="产品编码" prop="materialCode" min-width="160" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="物料代码" prop="materialOldNumber" min-width="160" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="产品名称" prop="materialName" min-width="160" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="规格型号" prop="specification" min-width="160" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="单位" prop="unit" min-width="100" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" label="订单数量" prop="qty" min-width="100" show-overflow-tooltip></el-table-column>
        </el-table>
        <div class="pagination clearfix" style="margin-top: 10px">
          <div class="fr">
            <el-pagination
              @current-change="handleTableCurrentChange"
              :current-page="currentPage"
              :page-size="10"
              background
              layout="prev, pager, next"
              :total="listTotal">
            </el-pagination>
          </div>
        </div>
      </div>
      
      <span slot="footer" class="dialog-footer">
        <el-button @click="closeDialog">取 消</el-button>
        <el-button type="primary" @click="submitAddGoods">确 定</el-button>
      </span>
    </el-dialog>

  </div>
</template>

<script>
import { getDetail, getGoodsList, addData, editData } from "@/api/supply/reserve";
import { getDictList } from '@/api/common'

let that
export default {
  name: 'ReserveForm',
  componentName: 'ReserveForm',
  props: ['listItem'],
  filters: {
    orderTypeFilter(val) {
      let obj = that.orderTypeList.find(o => o.value == val);
      return obj ? obj.label : ''
    }
  },
  data() {
    return {
      mainForm: {
        orderNum: '',
        orderDate: '',
        createMan: '',
        createDate: '',
        remark: '',
      },
      goodsList: [],
      tableSelection: [],

      typeList: [],
      orderTypeList: [
        { label: '商用单', value: 'TRADE' },
        { label: '家用单', value: 'HOME' },
        { label: '零售单', value: 'RETAIL' },
        { label: '销售政策单', value: 'RETAIL_POLICY' },
        { label: '置换家用单', value: 'PERMU_HOME' },
        { label: '置换商用单', value: 'PERMU_TRADE' },
        { label: '置换零售单', value: 'PERMU_RETAIL' },
        { label: '置换销售政策单', value: 'PERMU_RETAIL_POLICY' },
      ],
      isShowDialog: false,
      screenForm: {
        jxsNum: '',
        jxsName: '',
        type: '',
        goodsNum: '',
        goodsCode: '',
        goodsName: '',
        model: '',
        orderType: '',
        saleNum: '',
      },
      currentPage: 1,
      listTotal: 0,
      
      dialogGoodsList: [],
      dialogSelection: [],
    }
  },

  computed: {
    sidebar() {
      return this.$store.state.app.sidebar
    },
    classObj() {
      return {
        hideSidebar: !this.sidebar.opened,
        openSidebar: this.sidebar.opened
      }
    },
  },

  beforeCreate() {
    that = this;
  },

  created() {
    if(this.listItem) {
      this.getDetail();
    }else {
      this.mainForm.createMan = JSON.parse(localStorage.getItem("supply_user")).nickName;
      this.mainForm.createDate = this.getDate();
    }
  },

  methods: {
    getDate() {
      var date = new Date();
      var seperator1 = "-";
      var year = date.getFullYear();
      var month = date.getMonth() + 1;
      var strDate = date.getDate();
      if (month >= 1 && month <= 9) {
          month = "0" + month;
      }
      if (strDate >= 0 && strDate <= 9) {
          strDate = "0" + strDate;
      }
      var currentdate = year + seperator1 + month + seperator1 + strDate;
      return currentdate;
    },

    getDictList() {
      getDictList({sysDictEnum: 'PRODUCT_TYPE'}).then(res => {
        this.typeList = res.data;
      })
    },

    // 返回列表
    goBack() {
      this.$emit('backListFormDetail');
    },

    // 获取详情
    getDetail() {
      getDetail({id: this.listItem.id}).then(res => {
        let data = res.data;
        this.mainForm.orderNum = data.id;
        this.mainForm.orderDate = data.orderTime;
        this.mainForm.createMan = data.createBy;
        this.mainForm.createDate = data.createTime;
        this.mainForm.remark = data.remark;
        this.goodsList = data.reservedOrderItems;
      })
    },

    // 获取商品列表
    getGoodsList() {
      getGoodsList({
        pageNum: this.currentPage,
        pageSize: 10,
        customerNumber: this.screenForm.jxsNum,
        customerName: this.screenForm.jxsName,
        mainName: this.screenForm.type,
        materialCode: this.screenForm.goodsNum,
        materialOldNumber: this.screenForm.goodsCode,
        materialName: this.screenForm.goodsName,
        specification: this.screenForm.model,
        orderType: this.screenForm.orderType,
        orderId: this.screenForm.saleNum,
      }).then(res => {
        res.data.records.forEach(item => {
          item.status = 1;
        });
        let oldGoodsList = this.goodsList;
        let newGoodsList = res.data.records;
        for(let i = 0; i < oldGoodsList.length; i++) {
          let oldItem = oldGoodsList[i]
          for(let j = 0; j < newGoodsList.length; j++) {
            let newItem = newGoodsList[j]
            if(newItem.orderId === oldItem.orderId){
              newGoodsList[j].selected = true;
              break;
            }
          }
        }
        this.dialogGoodsList = newGoodsList;
        this.listTotal = res.data.total;
      })
    },

    // 查询重复值并禁选
    checkboxSelect(row, rowIndex) {
      if (row.selected) {
        return false // 禁用
      }else{
        return true // 不禁用
      }
    },

    // 点击 选择商品
    openDialog() {
      this.isShowDialog = true;
      this.getDictList();
      this.getGoodsList();
    },

    // 提交筛选表单
    submitScreenForm() {
      this.currentPage = 1;
      this.getGoodsList();
    },

    // 重置筛选表单
    resetScreenForm() {
      this.$refs.screenForm.resetFields();
      this.currentPage = 1;
      this.dialogGoodsList = [];
      this.getGoodsList();
    },

    // 更改列表当前页
    handleTableCurrentChange(val) {
      if(this.dialogSelection.length > 0) {
        return this.$errorMsg('已选择产品不可切换');
      }
      this.currentPage = val;
      this.getGoodsList();
    },

    // 关闭 弹窗
    closeDialog() {
      this.isShowDialog = false;
    },

    // 列表选择
    dialogSelectionChange(val) {
      this.dialogSelection = val;
    },

    // 确定 添加产品
    submitAddGoods() {
      this.goodsList = this.goodsList.concat(this.dialogSelection);
      this.isShowDialog = false;
      this.dialogGoodsList = [];
    },

    // 删除产品
    deleteItem(index) {
      this.goodsList.splice(index, 1);
    },

    // 修改状态
    changeItem(index, status) {
      this.goodsList[index].status = status;
    },

    tableSelectionChange(val) {
      this.tableSelection = val;
    },

    // 批量删除
    deleteGoods() {
      let goodsList = this.goodsList;
      let tableSelection = this.tableSelection;
      for(let i = 0; i < goodsList.length; i++) {
        for(let j = 0; j < tableSelection.length; j++) {
          if(tableSelection[j].orderId == goodsList[i].orderId){
            this.goodsList.splice(i, 1);
          }
        }
      }
    },

    // 提交
    clickSubmitForm() {
      this.$refs.mainForm.validate((valid) => {
        if (valid) {
          let params = {
            orderTime: this.mainForm.orderDate + ' 00:00:00',
            remark: this.mainForm.remark,
            reservedOrderItems: this.goodsList,
          }
          if(this.listItem) {
            params.id = this.listItem.id;
            editData(params).then(res => {
              this.$successMsg('编辑成功');
              this.goBack();
              this.$parent.getList();
            })
          }else {
            addData(params).then(res => {
              this.$successMsg('添加成功');
              this.goBack();
              this.$parent.getList();
            })
          }
        }
      })
    },
  }
}
</script>

<style scoped lang="scss">
  .detail-container {
    width: 100%;
    height: 100%;
  }
  .main-title {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-top: 20px;
    height: 60px;
    border-bottom: 1px solid #DCDFE6;
    margin-bottom: 20px;
    .title {
      font-size: 16px;
      font-weight: 600;
      padding-left: 10px;
    }
  }
</style>