<template>
  <div class="ServiceManageEdit">
    <div class="head-title">
      <span @click="CommonJump('ServiceMannage')" style="color:rgb(64, 158, 255);cursor:pointer;">服务人员管理</span><span
        style="margin:0 9px;color:#C0C4CC">/</span><span>服务人员编辑</span>
    </div>
    <div class="content">
      <el-form :model="addMsg" :rules="rules" ref="addMsg" label-width="100px" style="padding:0 20px;">
        <el-form-item label="头像">
          <div>
            <el-tooltip class="item" effect="dark" content="建议尺寸:88*88" placement="top-start">
              <el-button size="small" @click="choicImg=true">选择文件</el-button>
            </el-tooltip>
          </div>
          <div class="headerImg">
            <img v-if="addMsg.ServiceLogo" :src="addMsg.ServiceLogo" alt="" />
            <img v-else src="../../assets/img/default.png" alt="" />
          </div>
        </el-form-item>
        <el-form-item label="门店">
          <el-select class="w200" style="margin-right: 10px;" v-model="addMsg.StoreId" size="small" placeholder="请选择">
            <el-option v-for="item in StoreList" :key="item.Id" :label="item.Name" :value="item.Id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="从业年限">
          <el-input type="text" class="w200" size="small" @keyup.native="checkPrice(addMsg,'WorkYears')"
            v-model="addMsg.WorkYears">
            <template slot="append">年</template>
          </el-input>
        </el-form-item>
        <el-form-item label="对应的类型" prop="ServiceType">
          <div style="display: flex;flex-direction: row;align-items: center">
            <div @click="getUseType(1)" style="margin-right: 15px">
              <el-radio :label="1" v-model="addMsg.ServiceType">指定商品类型</el-radio>
            </div>
            <div @click='getUseType(2)' style="margin-right: 15px">
              <el-radio :label="2" v-model="addMsg.ServiceType">指定商品</el-radio>
            </div>
            <el-radio :label="3" v-model="addMsg.ServiceType" @change="getUseType2" style="margin-right: 15px">全部商品
            </el-radio>
          </div>
          <div class="splist" v-if="addMsg.ServiceType==1">
            <div v-for="(item,index) in AppointList" :label="item.ProductId" :key="index" style="margin-right: 20px;"
              class="el-tag el-tag--warning el-tag--plain">
              <span>{{item.Name}}</span>
              <i class="el-tag__close el-icon-close" @click="deleteProduct(item,index)"></i>
            </div>
          </div>
          <div class="splist" v-if="addMsg.ServiceType==2">
            <div v-for="(item,index) in commoditylist" :label="item.ProductId" :key="index"
              style="margin-right: 20px; position: relative; cursor: pointer;">
              <div class="app-image" :style="{backgroundImage:'url(' + item.CoverImage + ')',backgroundSize:'cover'}">
              </div>
              <i class="el-icon-error" style="position: absolute;right: -5px;top:-5px;color: #F56C6C;font-size: 20px"
                @click="deletecommod(item,index)"></i>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="名称" prop="Name">
          <el-input v-model="addMsg.Name" class="w400" size="small" placeholder="请输入服务人员名称" maxlength="20" />
        </el-form-item>
        <el-form-item label="性别">
          <el-radio-group v-model="addMsg.Gender">
            <el-radio :label="item.Id" v-for="(item,index) in genderList" :key="index">{{item.Name}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="标签">
          <el-tag :key="tag" size="small" style="margin-right:5px;" v-for="(tag,index) in addMsg.LableNameList" closable
            :disable-transitions="false" @close="handleClose(index)">
            {{tag}}
          </el-tag>
          <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput" size="mini"
            @keyup.enter.native="handleInputConfirm" @blur="handleInputConfirm">
          </el-input>
          <el-button class="button-new-tag" size="mini" @click="showInput">+ 标签</el-button>
        </el-form-item>
        <el-form-item label="虚拟预约数" style="display:none;">
          <el-input v-model="addMsg.FictitiousReserveNum" @keyup.native="checkInteger(addMsg,'FictitiousReserveNum')"
            class="w400" size="small" placeholder="请输入预约次数" maxlength="20" />
        </el-form-item>
        <el-form-item label="电话">
          <el-input type="number" v-model="addMsg.Telephone" class="w400" size="small" placeholder="请输入电话"
            maxlength="20" />
        </el-form-item>
        <el-form-item label="状态">
          <el-switch v-model="addMsg.ServiceStatus" active-color="#409EFF" :active-value="1" :inactive-value="2">
          </el-switch>
        </el-form-item>
        <el-form-item label="职务">
          <el-input v-model="addMsg.Major" class="w400" size="small" placeholder="职务" maxlength="20" />
        </el-form-item>
        <el-form-item label="简介">
          <el-input type="textarea" :rows="3" v-model="addMsg.Introduction" class="w400" size="small"
            placeholder="简介" />
        </el-form-item>
      </el-form>
    </div>
    <el-button size="small" style="margin-top:20px;padding:9px 25px;" type="primary" @click="submitform('addMsg')">保存
    </el-button>
    <!-- 选择图片文件 -->
    <el-dialog title="选择文件" :visible.sync="choicImg" width="1240px">
      <ChooseImg @SelectId="SelectId"></ChooseImg>
    </el-dialog>

    <!--已指定商品类别选择-->
    <el-dialog title="已指定商品类别" :visible.sync="category" width="714px">
      <div style="height:400px;overflow:auto;">
        <el-tree :data="ProductCategoryTreeList" show-checkbox :check-strictly="true" :check-on-click-node="true"
          default-expand-all node-key="Id" ref="tree" :default-checked-keys="checkedkeys" @check="TreeList"
          :props="defaultProps">
        </el-tree>
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button @click="category = false" size="small">取 消</el-button>
        <el-button type="primary" @click="getProductList" size="small">确 定</el-button>
      </div>
    </el-dialog>
    <!--选择的商品列表-->
    <el-dialog title="选择商品" :visible.sync="addcommodity" width="800px">
      <template>
        <div class="el-form-item">
          <div class="el-form-item__content">
            <div class="el-input el-input--small" style="width: 40%;">
              <input type="text" autocomplete="off" placeholder="商品名称" class="el-input__inner" v-model="msg2.Name"
                @clear="msg2.pageIndex=1,getProductGoodsPageList()" clearable>
            </div>
            <button type="button" class="el-button el-button--default el-button--small" style="margin-left: 15px"
              @click="msg2.pageIndex=1,getProductGoodsPageList()">查找商品</button>
            <button class="el-button el-button--default el-button--small" style="float: right;"
              @click="batchAdd">添加</button>
          </div>
        </div>
        <el-table v-loading="loading_t" :data="tableData" ref="dataTable" @selection-change="handleSelectionChange"
          style="width: 750px;height:400px;overflow:auto;">
          <el-table-column type="selection" width="55">
          </el-table-column>
          <el-table-column prop="Id" label="ID" width="100">
          </el-table-column>
          <el-table-column label="商品图" width="100">
            <template slot-scope="scope">
              <img style="width:50px;height:50px;margin-right:1px" :src="scope.row.CoverImage" alt="">
            </template>
          </el-table-column>
          <el-table-column prop="Name" label="商品名称">
          </el-table-column>
        </el-table>
        <el-pagination style="text-align:right" background @current-change="handleCurrentChange"
          :page-size="msg2.pageSize" layout="prev, pager, next" :current-page.sync="msg2.pageIndex" :total="count">
        </el-pagination>
      </template>
    </el-dialog>
  </div>
</template>
<script>
  import ChooseImg from "@/components/global/ChooseImg.vue";
  export default {
    data() {
      let validataType = (rule, value, callback) => {
        if (this.addMsg.ServiceType == '') {
          return callback(new Error('请选择对应类型'));
        } else {
          callback();
        }
      }
      return {
        //选择图片
        choicImg: false,
        //是否线下链接弹窗
        isShowLink: false,
        dataList: [],
        addMsg: {
          LableNameList: [], //	标签
          StoreId: '', //	店铺id
          Gender: 0, //性别
          ServiceType: '', //对应的类型
          ProductList: [], //商品信息
          ID: 0, //编号
          Name: '', //服务人员名称
          ServiceLogo: '', //头像、
          Major: '', //职务
          ServiceStatus: 1, //	启用/禁用 状态1启用 2禁用
          Telephone: '', //电话
          FictitiousReserveNum: 0, //虚拟预约数
          WorkYears: '', //工作年限
          Introduction: '' //简介 
        },
        msg2: {
          pageIndex: 1,
          pageSize: 15,
          Name: '',
          GoodsStatus: 1,
          IsSelectSellOut: 0,
          CategoryIds: '',
          Id: 0,
          StartTime: '',
          EndTime: '',
          StoresIds: "",
        },
        genderList: [], //性别枚举
        inputValue: '', //新增标签输入框值
        inputVisible: false, //切换新增标签输入框
        category: false,
        defaultProps: {
          children: 'ChildList',
          label: 'Name'
        },
        ProductCategoryTreeList: [],
        checkedkeys: [], //默认选中的
        AppointList: [], //指定商品分类
        addcommodity: false,
        commoditylist: [], //商品的list
        loading_t: false,
        tableData: [],
        multipleSelection: [],
        count: 0,
        cityOptions: [],
        cities: [],
        SmallShopData: [],
        SmallShopMsg: {
          Name: ''
        },
        StoreList: [], //门店下拉数据
        AppointList2: [],
        rules: {
          Name: [{
            required: true,
            message: "请输入服务人员名称",
            trigger: "blur"
          }],
          ServiceType: [{
            validator: validataType,
            trigger: "blur",
            required: true
          }]
        }
      };
    },
    components: {
      ChooseImg
    },
    created() {

    },
    methods: {
      //新增标签
      showInput() {
        this.inputVisible = true;
        this.$nextTick(_ => {
          this.$refs.saveTagInput.$refs.input.focus();
        });
      },
      handleInputConfirm() {
        if (this.inputValue) {
          this.addMsg.LableNameList.push(this.inputValue);
        }
        this.inputVisible = false;
        this.inputValue = '';
      },
      //获取性别
      getMale() {
        this.apipost("/api/Reserve/GetGenderEnumList", {}, res => {
          if (res.data.resultCode == 1) {
            this.genderList = res.data.data;
          } else {
            this.Error(res.data.message);
          }
        })
      },
      //删除标签
      handleClose(index) {
        this.addMsg.LableNameList.splice(index, 1);
      },
      //操作对应商品类型
      getUseType(val) {
        if (val == 1) {
          this.category = true;
          this.$nextTick(() => { //在弹出dialog之前执行$nextTick回调函数，确保el-tree已经渲染
            this.$refs.tree.setCheckedKeys(this.checkedkeys);
          });
          this.commoditylist=[];
        } else if (val == 2) {
          this.tableData = [];
          this.count = 0;
          this.checkedkeys = []
          this.addcommodity = true
          this.getProductGoodsPageList();
          this.AppointList=[];
        }
      },
      TreeList(val, e) {
        this.eData = e
      },
      getUseType2() {
        this.checkedkeys = []
      },
      //新增对应商品类型
      getProductList() {
        this.category = false;
        let e = this.eData;
        let ProductList = []
        this.checkedkeys = e.checkedKeys;
        if (e.checkedNodes.length > 0) {
          this.checkedkeys.forEach(x => {
            var objList = this.getObjById(this.ProductCategoryTreeList, x);
            if (objList) {
              for (var i = 0; i < this.AppointList.length; i++) {
                if (this.AppointList[i].ProductId == objList.Id) {
                  return;
                }
              }
              this.AppointList.push({
                ProductId: objList.Id,
                Name: objList.Name
              })
            }
          })
        }
      },
      //删除对应商品类型
      deleteProduct(item, index) {
        this.AppointList.splice(index, 1)
        for (let i = 0; i < this.checkedkeys.length; i++) {
          if (this.checkedkeys[i] == item.ProductId) {
            this.checkedkeys.splice(i, 1)
          }
        }
      },
      deletecommod(data, index) {
        this.tableData.forEach(x => {
          if (data.Id == x.Id) {
            x.disabled = false
            this.commoditylist.splice(index, 1)
          }
        })
      },
      getProductGoodsPageList() {

        this.msg2.StoresIds = this.addMsg.StoreId;
        if (this.msg2.StoresIds == '' || this.msg2.StoresIds == '0') {
          this.Error("请选择门店!");
          return;
        }
        this.loading_t = true;
        this.apipost("/api/OSGoods/GetOfflineGoodsPageList", this.msg2, res => {
          this.loading_t = false;
          if (res.data.resultCode == 1) {
            this.tableData = res.data.data.pageData
            this.count = res.data.data.count
          }
        })
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      addtableData(data) {
        var myTable = JSON.parse(JSON.stringify(this.tableData));
        myTable[data.$index].disabled = true;
        this.commoditylist.push(data.row)
        this.tableData = myTable;
        this.Success('添加成功');
      },
      handleCurrentChange(val) {
        this.msg2.pageIndex = val;
        this.getProductGoodsPageList();
      },
      batchAdd() { //批量添加
        let newdata = []
        for (let i = 0; i < this.multipleSelection.length; i++) {
          if (this.commoditylist.length > 0) {
            for (let j = 0; j < this.commoditylist.length; j++) {
              if (this.multipleSelection[i].Id != this.commoditylist[j].Id) {
                newdata.push(this.multipleSelection[i])
                for (let z = 0; z < this.tableData.length; z++) {
                  if (this.tableData[z].Id == this.multipleSelection[i].Id) {
                    this.tableData[z].disabled = true;
                    break
                  }
                }
              }
            }
          } else {
            newdata.push(this.multipleSelection[i])
            for (let z = 0; z < this.tableData.length; z++) {
              if (this.tableData[z].Id == this.multipleSelection[i].Id) {
                this.tableData[z].disabled = true;
                break
              }
            }
          }
        }
        if (newdata.length > 0) {
          this.Success('添加成功');
        }
        this.commoditylist = this.unique(this.commoditylist.concat(newdata))
        this.$refs.dataTable.clearSelection();
        this.addcommodity = false;
      },
      // 数组去重
      unique(arr) {
        for (var i = 0, len = arr.length; i < len; i++) {
          for (var j = i + 1, len = arr.length; j < len; j++) {
            if (arr[i].Id === arr[j].Id) {
              arr.splice(j, 1);
              j--; // 每删除一个数j的值就减1
              len--; // j值减小时len也要相应减1（减少循环次数，节省性能）
            }
          }
        }
        return arr;
      },
      getMemberGradeList() {
        this.cityOptions = [];
        this.apipost("/api/User/GetMemberGradeList", {}, res => {
          this.cities = res.data.data;
          let data = res.data.data;
          data.forEach(item => {
            this.cityOptions.push(item.Id)
          })
        })
        this.getProductCategoryTreeList()
      },
      getProductCategoryTreeList() {
        this.apipost("/api/AppletGoods/GetProductCategoryTreeList", {}, res => {
          if (res.data.resultCode == 1) {
            this.ProductCategoryTreeList = res.data.data
          } else {
            this.Error(res.data.message);
          }
        })
      },
      getSmallShopsDropDownList() {
        this.apipost("/api/SmallShops/GetAllSmallShopsList", this.SmallShopMsg, res => {
          this.loading = false
          if (res.data.resultCode == 1) {
            this.SmallShopData = res.data.data
          } else {
            this.Error(res.data.message);
          }
        })
      },

      //选择图片
      SelectId(msg) {
        this.addMsg.ServiceLogo = this.getIconLink(msg.url);
        this.choicImg = false;
      },
      submitform(addMsg) {
        //提交创建、修改表单
        this.$refs[addMsg].validate(valid => {
          if (valid) {
            this.saveMsg();
          } else {
            return false;
          }
        });
      },
      getStoreList() {
        this.apipost("/api/MContent/GetStoresList", {}, res => {
          if (res.data.resultCode == 1) {
            this.StoreList = res.data.data;
          } else {
            this.Error(res.data.message);
          }
        })
      },
      //保存
      saveMsg() {
        if (this.addMsg.ServiceType == 2) {
          let ProductList = []
          for (let i = 0; i < this.commoditylist.length; i++) {
            ProductList.push({
              'ProductId': this.commoditylist[i].Id,
            })
          }
          this.addMsg.ProductList = ProductList
        } else if (this.addMsg.ServiceType == 1) {
          let ProductList = []
          for (let i = 0; i < this.AppointList.length; i++) {
            ProductList.push({
              'ProductId': this.AppointList[i].ProductId,
            })
          }
          this.addMsg.ProductList = ProductList
        }
        this.apipost("/api/Reserve/AddOrUpdateServicePersonal", this.addMsg, res => {
          if (res.data.resultCode == 1) {
            this.Success(res.data.message);
            this.$router.go(-1); //返回上一层
          } else {
            this.Error(res.data.message);
          }
        })
      },
      //获取数据
      getData() {
        this.apipost("/api/Reserve/GetServicePersonalModel", {
          ID: this.addMsg.ID
        }, res => {
          if (res.data.resultCode == 1) {
            this.addMsg = res.data.data;
            if (res.data.data.ServiceType == 1) {
              let ProductList = res.data.data.ProductList;
              this.AppointList = []
              this.getProductCategoryTreeList();
              for (let i = 0; i < ProductList.length; i++) {
                this.checkedkeys.push(ProductList[i].ProductId)
                var objList = this.getObjById(this.ProductCategoryTreeList, ProductList[i].ProductId);
                if (objList) {
                  this.AppointList.push({
                    ProductId: objList.Id,
                    Name: objList.Name
                  })
                }
              }
            }
            if (res.data.data.ServiceType == 2) {
              this.commoditylist = [];
              var myTable = [];
              this.apipost("/api/OSGoods/GetOfflineGoodsPageList", this.msg2, res => {
                if (res.data.resultCode == 1) {
                  myTable = res.data.data.pageData;
                }
                myTable.forEach(x => {
                  this.addMsg.ProductList.forEach(y => {
                    if (y.ProductId == x.Id) {
                      this.commoditylist.push(x);
                      x.disabled = true;
                    }
                  })
                })
                this.tableData = myTable;
              })
            }
          } else {
            this.Error(res.data.message);
          }
        })
      },
      getObjById(list, id) {
        if (!list instanceof Array) {
          return null
        }
        //遍历数组
        for (let i in list) {
          let item = list[i]
          if (item.Id === id) {
            return item
          } else {
            //查不到继续遍历
            if (item.ChildList) {
              let value = this.getObjById(item.ChildList, id)
              //查询到直接返回
              if (value) {
                return value
              }
            }
          }
        }
      }
    },
    mounted() {
      this.getMale();
      this.getMemberGradeList();
      this.getSmallShopsDropDownList();
      this.getStoreList();
      if (this.$route.query.ID) {
        this.addMsg.ID = this.$route.query.ID;
        this.getData()
      }
    }
  };

</script>
<style>
  .ServiceManageEdit .headerImg {
    width: 80px;
    height: 80px;
  }

  .ServiceManageEdit .headerImg img {
    width: 100%;
    height: 100%;
  }

  .ServiceManageEdit .content {
    background: #fff;
    margin-top: 10px;
    padding: 20px;
    box-sizing: border-box;
  }

  .ServiceManageEdit .app-image {
    width: 50px;
    height: 50px;
    border-radius: 0%;
    background-position: center center;
  }

  .ServiceManageEdit .splist {
    display: flex;
    flex-wrap: wrap;
  }

  .ServiceManageEdit .input-new-tag {
    width: 90px;
    margin-left: 10px;
    vertical-align: bottom;
  }

</style>
