<template>
  <div class="app-container">
        <el-form ref="form" :model="form" :rules="rules" label-width="100px">
           <el-form-item label="客户信息" prop="crmId">
                <el-row  >
                  <el-col >
                    <el-input placeholder="请输入客户手机号" clearable style="width:240px;cursor:pointer" v-model="phone">
                    </el-input>
                    <el-button plain style="margin-left:10px;"    @click="searchUser()">查询</el-button>
                  </el-col>
                </el-row>
                <el-table border style="margin-top:5px;"  v-loading="userloading" :data="users">
                  <el-table-column label="ID" align="center" prop="customerId" />
                  <el-table-column label="客户编码" align="center" prop="customerCode" />
                  <el-table-column label="客户名称" align="center" prop="customerName" />
                  <el-table-column label="手机号" align="center" prop="mobile" />
                  <el-table-column  label="客户来源" align="center" prop="source">
                    <template slot-scope="scope">
                      <el-tag prop="status" v-for="(item, index) in sourceOptions"    v-if="scope.row.source==item.dictValue">{{item.dictLabel}}</el-tag>
                    </template>
                  </el-table-column>
                </el-table>
            </el-form-item>
            <el-form-item label="商品列表" >
              <el-row  >
                <el-col >
                      <el-button plain  type="primary" icon="el-icon-plus" @click="handleAddProduct">添加商品</el-button>
                </el-col>
              </el-row>
              <el-table border :key = "tablekey" width="100%" style="margin-top:5px;"  :data="products">
                <el-table-column label="商品编号" align="center" prop="barCode" />
                <el-table-column label="商品图片" align="center" width="100">
                  <template slot-scope="scope">
                    <el-popover
                      placement="right"
                      title=""
                      trigger="hover"
                    >
                      <img slot="reference" :src="scope.row.image" width="50">
                      <img :src="scope.row.image" style="max-width: 50px;">
                    </el-popover>
                  </template>
                </el-table-column>
                <el-table-column label="商品名称" show-overflow-tooltip align="center" prop="productName" />
                <el-table-column label="商品规格" align="center" prop="sku" />
                <el-table-column label="单价" align="center" prop="price" />
                <el-table-column label="数量" align="center"  prop="count" width="200px" :key="tablekey">
                   <template slot-scope="scope">
                    <div>
                        <el-input-number v-model="scope.row.count"  @change="handleProductCountChange(scope.row)"  size="mini" :min="1"   ></el-input-number>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="小计" align="center" prop="money"   />
                <el-table-column label="操作" align="center" width="100px" >
                  <template slot-scope="scope">
                    <el-button
                      size="mini"
                      type="text"
                      icon="el-icon-delete"
                      @click="handleDelete(scope.row)"
                    >删除</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-row>
                <el-col>
                      <span>商品合计:{{products.length}}</span><span style="margin-left:10px;">商品总价:{{totalMoney.toFixed(2)}}</span>
                </el-col>
              </el-row>
            </el-form-item>
            <el-form-item label="核实业务员" prop="uploadUserId">
              <el-select style="width:220px" v-model="form.uploadUserId" placeholder="请选择" clearable size="small" >
                <el-option
                  v-for="item in salesmanList"
                  :key="item.dictValue"
                  :label="item.dictLabel"
                  :value="item.dictValue"
                />
              </el-select>
            </el-form-item>
            <el-form-item label="价格" prop="payPrice">
              <el-input-number v-model="form.payPrice"  size="mini"    ></el-input-number>
            </el-form-item>
            <el-form-item label="订单备注" prop="remark">
              <el-input  type="textarea" rows="2" v-model="form.remark" placeholder="" />
            </el-form-item>
        </el-form>
      <div slot="footer" class="dialog-footer" style="float: right; margin-bottom: 20px;">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    <el-dialog :title="product.title" v-if="product.open"  :visible.sync="product.open" width="1000px" append-to-body>
        <product-select  @selectProduct="selectProduct" />
    </el-dialog>


  </div>
</template>

<script>
import { getMyCustomerList,recover,exportCustomer  } from "@/api/crm/customer";
import {createOrder} from "@/api/hisStore/storeOrderOffline";
import { getSalesman } from "@/api/company/companyUser";


import productSelect from "@/views/hisStore/components/productSelect";

export default {
  components: { productSelect },
  name: "AddOrderOffline",
  data() {
    return {
      salesmanList:[],
      tablekey:false,
      totalMoney:0.00,
      products:[],
      product:{
        open:false,
        title:"商品选择"
      },
      phone:null,

      userloading: false,
      users:[],
      sourceOptions:[],
      userStatusOptions:[],
      statusOptions:[],
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,

      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 订单表格数据
      storeOrderList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,


      // 表单参数
      form: {
        crmId:null,
        uploadUserId:null,
        products:[],
      },
      // 表单校验
      rules: {
        crmId: [
          { required: true, message: "客户信息不能为空", trigger: "submit" }
        ],
        uploadUserId: [
          { required: true, message: "核实业务员不能为空", trigger: "blur" }
        ],

        products: [
          { required: true, message: "商品不能为空", trigger: "submit" }
        ],

      }
    };
  },
  created() {
    this.getDicts("crm_customer_source").then((response) => {
      this.sourceOptions = response.data;
    });
    getSalesman().then((response) => {
      this.salesmanList = response.data;
    });
  },
  methods: {
    handleAddProduct(){
      this.product.open=true;
    },
    compute(){
      this.totalMoney=0;
      var that=this;
      this.products.forEach (function (value) {
          that.totalMoney += value.money;
      });
    },
    handleProductCountChange(row){
      this.tablekey = !this.tablekey
      row.money=row.count*row.price;
      this.$forceUpdate();
      this.compute();
    },
    selectProduct(row){
      for(var i=0;i<this.products.length;i++){
        if(this.products[i].id===row.id){
          this.$message.warning("商品已存在")
          return;
        }
      }
      row.count=1;
      row.money=row.count*row.price;
      this.products.push(row);
      this.compute();
      this.$message.success("商品添加成功")
    },

    searchUser(crmId){
      if(this.phone==null||this.phone===""){
        return;
      }
      var data={mobile:this.phone}
      this.userloading = true;
      this.users=[];
      getMyCustomerList(data).then(response => {
        this.users = response.rows;
        this.userloading = false;
        if(this.users!=null&&this.users.length===1){
          this.form.crmId=this.users[0].customerId;
        }
      });
    },

    // 取消按钮
    cancel() {
      this.$emit("closeOrderOffline")
    },
    // 表单重置
    reset() {
      this.form = {

        userId:null,
        products:null,

      };
      this.resetForm("form");
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if(this.products.length==0){
          this.msgError("请选择商品");
          return;
        }
        this.form.products=this.products;
        if (valid) {
          createOrder(this.form).then(response => {
            if (response.code === 200) {
              this.msgSuccess("创建成功");
              this.$emit("closeOrderOffline")
            }
          });

        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
       this.products.splice(this.products.findIndex(item => item.id === row.id), 1)
       this.compute();

    },

  }
};
</script>
<style scoped lang="scss">
.items{
  margin: 5px 0px;
  display: flex;
  flex-direction: row;
  align-items: center;
  justify-content: flex-start;
  .pic{
    width:60px;
    height:60px;
  }
  .goods-content{
    margin-left: 10px;
    max-width: 200px;
    text-align: left;
    .goods-title{

      overflow:hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      -o-text-overflow:ellipsis;
    }
  }
}
.el-message-box__message p{
  max-height: 400px;
  overflow:scroll;
}
.import-msg{
  height: 500px;
  overflow: auto;
}
</style>
<style>
  .el-descriptions-item__label.is-bordered-label{
    font-weight: normal;
  }

</style>
