<!--
 * @Description: 新增/编辑弹框
 * @Author: Sugar.
 * @Date: 2023-11-24 13:55:00
 * @LastEditors: Sugar.
 * @LastEditTime: 22023-11-24 13:55:00
 * @FilePath: \cattle_webui\src\views\team\teamMr\AddOrEditDialog.vue
 * @Copyright: Copyright (c) 2016~2023 by Sugar., All Rights Reserved.
-->
<template>
  <el-dialog
    :title="title"
    :visible.sync="open"
    width="700px"
    append-to-body
    :close-on-click-modal="false"
    @close="cancel"
  >
    <div class="dialog">
      <el-form :model="form" ref="form" :rules="rules" label-width="150px">
        <!-- <el-form-item v-if="form.checkRemark" label="驳回原因:">
          <span>{{ form.checkRemark }}</span>
        </el-form-item> -->
        <el-form-item label="客户类型" prop="bigCustomer">
          <el-radio-group v-model="form.bigCustomer">
            <el-radio :label="1">普通客户</el-radio>
            <el-radio :label="2">大客户</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="团队名称:" prop="name">
          <!-- <el-popover
            placement="bottom-start"
            title=""
            trigger="manual"
            v-model="showNameList"
            >
            <div 
            style="text-align: right; margin: 0;min-width: 300px;min-height: 200px;"
            v-loading="nameListLoading"
            >
              <div 
              v-for="(item,index) in nameList" 
              :key="index"
              @click="setNanmeList(item,index)"
              class="team_name_list"
              >
                <span style="">{{ item.name }}</span>
              </div>
            </div>
            <el-input
              slot="reference"
              v-model="form.name"
              placeholder="团队名称"
              clearable
              @blur="showNameList = false"
              @focus="showNameList = true"
              @input="getList"
              style="width: 100%;"
            />
          </el-popover> -->
          <el-select
            v-model="form.name"
            filterable
            remote
            reserve-keyword
            clearable
            style="width: 100%"
            placeholder="请输入团队名称"
            :remote-method="getList"
            :loading="nameListLoading">
            <el-option
              v-for="item in nameList"
              :key="item.companyName"
              :label="item.companyName"
              :value="item.companyName">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="团队类型:" prop="type">
          <el-select
            v-model="form.type"
            placeholder="团队类型"
            clearable
            style="width: 100%;"
            @change="changeType"
          >
            <el-option
              v-for="dict in dict.type.team_type"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="OTA来源:" prop="source" v-if="form.type == 6">
          <el-select
            v-model="form.source"
            placeholder="OTA来源"
            clearable
            style="width: 100%;"
          >
            <el-option
              v-for="dict in listType"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="销售员:" prop="salerPerson">
          <el-input
            v-model="form.salerPerson"
            placeholder="销售员"
            clearable
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="销售员联系电话:" prop="salerMobile">
          <el-input
            v-model="form.salerMobile"
            placeholder="销售员联系电话"
            clearable
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="客户负责人:" prop="contact">
          <el-input
            v-model="form.contact"
            placeholder="客户负责人"
            clearable
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="客户账号/联系电话:" prop="mobile">
          <el-input
            v-model="form.mobile"
            placeholder="客户账号/联系电话"
            clearable
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="密码">
          <el-input
            show-password
            v-model="form.password"
            autocomplete="new-password"
            placeholder="密码"
            clearable
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="是否有合同" prop="haveContract">
          <el-radio-group v-model="form.haveContract">
            <el-radio :label="0">无</el-radio>
            <el-radio :label="1">有</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.haveContract == 1" label="合约信息:" prop="photoList">
          <el-upload
            ref="upload"
            :action="uploadObj.url"
            :headers="uploadObj.headers"
            accept=".jpg,.png"
            :on-success="handlePhotoListSuccess"
            :before-upload="beforeAvatarUpload"
            list-type="picture-card"
            :file-list="form.photoList"
            :on-remove="handleRemove"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item>
        <el-form-item v-if="form.haveContract == 0" label="无合约原因" prop="contractReason">
          <el-input
            v-model="form.contractReason"
            placeholder="请输入无合约原因"
            clearable
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="备注:" prop="remark">
          <el-input
            v-model="form.remark"
            placeholder="该字段主要用于相同团队的区分，请谨慎填写"
            clearable
            style="width: 100%;"
          />
        </el-form-item>
        <el-form-item label="绑定团队:" prop="bindTeamId">
          <el-select
            v-model="form.bindTeamId"
            filterable
            remote
            :disabled="isDisabled"
            reserve-keyword
            clearable
            style="width: 82%;margin-right: 8px;"
            placeholder="请输入关键词进行查询并绑定"
            :remote-method="getTeamList"
            :loading="teamListLoading"
          >
            <el-option
              v-for="item in teamList"
              :key="item.id"
              :label="item.name"
              :value="item.id">
            </el-option>
          </el-select>
          <el-button type="primary" :disabled="!isDisabled" @click="removeBind">解绑</el-button>
        </el-form-item>
      </el-form>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="cancel">取消</el-button>
      <el-button
        type="primary"
        @click="submitForm"
        v-loading.fullscreen.lock="loading"
        element-loading-text="提交中..."
        element-loading-spinner="el-icon-loading"
        element-loading-background="rgba(0, 0, 0, 0.8)"
      >
        <span v-if="loading">提交中...</span>
        <span v-else>保存</span>
      </el-button>
    </span>
  </el-dialog>
</template>

<script>
// import { updateNoticeMgr } from "@/api/system/noticeMgr";
import { pageList, removeBindApi } from '@/api/team/teamMr'
import { saveAndEdit, getSelectById, searchCompanysApi } from "@/api/team/teamMr";
import Editor from "@/components/Editor";
import { getToken } from "@/utils/auth";

export default {
  name: "addAndEdit",
  props: {
    dict: {
      type: Object,
      default: () => [],
    },
  },
  components: {
    Editor,
  },
  data() {
    return {
      title: "编辑",
      model: "EDIT",
      activeName: '01',
      open: false,
      loading: false,
      form: {
        id: undefined,
        type: "",
      },
      listType: [
          {
              "label": "窗口美团",
              "value": 10,
          },
          {
              "label": "窗口携程",
              "value": 11,
          },
          {
              "label": "窗口抖音",
              "value": 13,
          },
          {
              "label": "窗口猫眼",
              "value": 14
          },
          {
              "label": "窗口大麦",
              "value": 18,
          },
          {
              "label": "窗口飞猪",
              "value": 19,
          }
      ],
      rules: {
        bigCustomer: [{ required: true, message: "请输入客户类型", trigger: ["change","blur"] }],
        name: [{ required: true, message: "请输入团队名称", trigger: ["change","blur"] }],
        type: [{ required: true, message: "请选择团队类型", trigger: ["change","blur"] }],
        source: [{ required: true, message: "请选择OTA来源", trigger: ["change","blur"] }], 
        contact: [{ required: true, message: "请输入客户负责人", trigger: ["change","blur"] }],
        mobile: [{ required: true, message: "请输入客户账号/联系电话", trigger: ["change","blur"] }],
        salerPerson: [{ required: true, message: "请输入销售员", trigger: ["change","blur"] }],
        salerMobile: [{ required: true, message: "请输入销售员联系电话", trigger: ["change","blur"] }],

        haveContract: [{ required: true, message: "请选择是否有合同", trigger: ["change","blur"] }],
        photoList: [{ required: true, message: "请上传合约信息图片", trigger: ["change","blur"] }],
        contractReason: [{ required: true, message: "请输入无合约原因", trigger: ["change","blur"] }],
      },
      uploadObj: {
        url: process.env.VUE_APP_UPLOAD_FILE_API + "/upload/single/minio",
        Headers: { Authorization: "Bearer " + getToken() },
      },
      nameList: [],
      nameListTime: null,
      nameListLoading: null,
      showNameList: false,
      teamList: [],
      teamListTime: null,
      teamListLoading: null,
      isDisabled: false,
      rowId: "",
    };
  },
  methods: {
    /**
     * 打开弹框
     * @date 2023-11-22
     * @param {any} obj
     * @returns {any}
     */
    openDialog(title, obj) {
      this.open = true;
      this.nameList = []
      this.reset();
      if (obj){
        this.title = "编辑团队";
        this.getSelectByIdApi(obj);
      }else{
        this.form.bigCustomer = 1
        this.title = "添加团队";
        this.$nextTick(() => {
          this.$refs["form"].clearValidate();
        });
      }
    },
    /** 查询团队列表 */
    getTeamList(value) {
      if(!value) {
        this.teamList = []
        return
      }
      if(this.teamListTime) {
        clearTimeout(this.teamListTime)
      }
      this.teamListTime = setTimeout(()=>{
        this.teamListLoading = true;
        this.teamList = []
        pageList({
          pageNum: 1,
          pageSize: 999,
          name: value,
          checkStatus: 1
        })
        .then(response => {
            let teamArr = response.data.rows || []
            if(teamArr.length != 0) {
              this.teamList = teamArr.filter(ele => ele.id != this.rowId)
            } else {
              this.teamList = []
            }
            this.teamListLoading = false;
          }
        ).catch(()=>{
          this.teamList = []
          this.teamListLoading = false;
        })
      },1000)
    },
    /** 查询列表 */
    getList(value) {
      if(!value) {
        this.nameList = []
        return
      }
      if(this.nameListTime) {
        clearTimeout(this.nameListTime)
      }
      this.nameListTime = setTimeout(()=>{
        this.nameListLoading = true;
        this.nameList = []
        searchCompanysApi({
          companyName: value,
        })
        .then(response => {
            this.nameList = response.data.list;
            this.nameListLoading = false;
          }
        ).catch(()=>{
          this.nameList = []
          this.nameListLoading = false;
        })
      },1000)
      
    },
    async setNanmeList(item,index){
      this.nameLoading = false
      return
      this.$set(this.form,'name',item.name)
    },
    /** 获取详情 */
    getSelectByIdApi(row) {
      const id = row.id
      getSelectById(id).then(response => {
        const obj = response.data;
        this.rowId = obj.id;
        if(obj.bindTeamId) {
          let index = obj.bindTeamName.indexOf("(");
          let resVal = index === -1 ? obj.bindTeamName : obj.bindTeamName.substring(0, index); 
          this.getTeamList(resVal);
          this.isDisabled = true
        } else {
          this.isDisabled = false
        }
        this.$nextTick(() => {
          this.$nextTick(() => {
            this.$set(this.form, 'id', obj.id);
            this.$set(this.form, 'bigCustomer', obj.bigCustomer);
            this.$set(this.form, 'name', obj.name);
            this.$set(this.form, 'type', obj.type + '');
            this.$set(this.form, 'source', obj.source)
            this.$set(this.form, 'contact', obj.contact);
            this.$set(this.form, 'password', "");
            this.$set(this.form, 'mobile', obj.mobile);
            this.$set(this.form, 'salerPerson', obj.salerPerson);
            this.$set(this.form, 'salerMobile', obj.salerMobile);
            this.$set(this.form, 'checkRemark', obj.checkRemark);
            this.$set(this.form, 'haveContract', obj.haveContract);
            this.$set(this.form, 'contractReason', obj.contractReason);
            this.$set(this.form, 'remark', obj.remark);
            this.$set(this.form, 'bindTeamId', obj.bindTeamId);
            this.changeType(this.form.type)
            if(obj.contractImg){
              if(obj.contractImg.indexOf(',') > -1){
                let img_list = obj.contractImg.split(',');
                let img_list_new = [];
                img_list.forEach((item, index) => {
                  img_list_new.push({
                    url: item,
                  })
                });
                this.$set(this.form, 'photoList', img_list_new);
              } else {
                this.$set(this.form, 'photoList', [{url: obj.contractImg}]);
              }
            } else {
              this.$set(this.form, 'photoList', []);
            }
            this.$nextTick(() => {
              this.$refs["form"].clearValidate();
            });
          });
        });
      });
    },
    // 团队解绑 // bindTeamName
    removeBind() {
      removeBindApi(this.form.id).then(res => {
        if(res.code === 200) {
          this.$message.success("解绑成功!");
          this.$set(this.form, 'bindTeamId', '');
          this.isDisabled = false
        }
        }).catch(()=>{
      })
    },
    /**
     * 保存
     * @date 2023-11-22
     * @returns {any}
     */
    submitForm() {
      this.$refs["form"].validate(async (valid) => {
        if (valid) {
          try {
            this.loading = true;
            this.form.contractImg = '';
            this.form.photoList.forEach((item, index) => {
              if(index < this.form.photoList.length - 1) {
                this.form.contractImg += item.url + ",";
              } else {
                this.form.contractImg += item.url;
              }
            })
            const { code } = await saveAndEdit({ ...this.form });
            if (code === 200) {
              this.$message.success("操作成功!");
              this.$emit("getList");
              this.cancel();
            }
          } catch (error) {
          } finally {
            this.loading = false;
          }
        }
      });
    },
    /**
     * 重置
     * @date 2023-11-22
     * @returns {any}
     */
    reset() {
      this.$set(this.form, 'id', "");
      this.$set(this.form, 'bigCustomer', '');
      this.$set(this.form, 'name', "");
      this.$set(this.form, 'type', "");
      this.$set(this.form, 'source', "")
      this.$set(this.form, 'contact', "");
      this.$set(this.form, 'password', "");
      this.$set(this.form, 'mobile', "");
      this.$set(this.form, 'photoList', []);
      this.$set(this.form, 'salerPerson', '');
      this.$set(this.form, 'salerMobile', '');
      this.$set(this.form, 'checkRemark', '');
      this.$set(this.form, 'haveContract', '');
      this.$set(this.form, 'contractReason', '');
      this.$set(this.form, 'remark', '');
      this.$set(this.form, 'bindTeamId', '');
      this.isDisabled = false;
    },
    /**
     * 关闭弹框
     * @date 2023-11-22
     * @returns {any}
     */
    cancel() {
      this.reset();
      this.open = false;
    },
    /**
     * 上传成功
     * @date 2023-11-22
     * @param {any} res
     * @returns {any}
     */
    handleAvatarSuccess(res) {
      if (res.code === 200) {
        // this.form.mainImg = res?.data?.url;
        this.$set(this.form, 'mainImg', res?.data?.url)
      }
    },
    /**
     * 上传文件之前之前
     * @date 2023-11-22
     * @param {any} file
     * @returns {any}
     */
    beforeAvatarUpload(file) {
      const isJPG = file.type === "image/jpeg" || "image/png";
      if (!isJPG) {
        this.$message.error("上传头像图片只能是jpg或png格式!");
      }
      return isJPG;
    },
    /**
     * 剧目海报上传成功
     * @date 2023-11-22
     * @param {any} res
     * @returns {any}
     */
    handlePhotoListSuccess(res) {
      if (res.code === 200) {
        let photo = {
          imageUrl: res?.data?.url,
          url: res?.data?.url,
          photoType: '2'
        }
        if(!this.form.photoList){
          this.form.photoList = []
        }
        // this.form.photoList.push(photo);
        this.$set(this.form.photoList, this.form.photoList.length, photo);
      }
    },
    handleRemove(file, fileList) {
      this.form.photoList.forEach((item, index) => {
        if(item.uid == file.uid){
          this.form.photoList.splice(index, 1)
        }
      })
    },
    /**  选择团队类型  */
    changeType(value) {
      if(value == 6) {
        this.rules = {
          ...this.rules,
          contact: [{ required: false, message: "请输入客户负责人", trigger: ["change","blur"] }],
          mobile: [{ required: false, message: "请输入客户账号/联系电话", trigger: ["change","blur"] }],
          salerPerson: [{ required: false, message: "请输入销售员", trigger: ["change","blur"] }],
          salerMobile: [{ required: false, message: "请输入销售员联系电话", trigger: ["change","blur"] }],

          haveContract: [{ required: false, message: "请选择是否有合同", trigger: ["change","blur"] }],
          photoList: [{ required: false, message: "请上传合约信息图片", trigger: ["change","blur"] }],
          contractReason: [{ required: false, message: "请输入无合约原因", trigger: ["change","blur"] }],
        
        }
      }else {
        this.rules = {
          ...this.rules,
          contact: [{ required: true, message: "请输入客户负责人", trigger: ["change","blur"] }],
          mobile: [{ required: true, message: "请输入客户账号/联系电话", trigger: ["change","blur"] }],
          salerPerson: [{ required: true, message: "请输入销售员", trigger: ["change","blur"] }],
          salerMobile: [{ required: true, message: "请输入销售员联系电话", trigger: ["change","blur"] }],

          haveContract: [{ required: true, message: "请选择是否有合同", trigger: ["change","blur"] }],
          photoList: [{ required: true, message: "请上传合约信息图片", trigger: ["change","blur"] }],
          contractReason: [{ required: true, message: "请输入无合约原因", trigger: ["change","blur"] }],
          
        }
        this.$refs["form"].clearValidate();
      }
    }
  },
};
</script>

<style lang="scss" scoped>
.dialog {
  padding: 0 30px;
  max-height: 65vh;
  overflow-y: auto;
}
.dialog {
  padding: 0 30px;
  .upload-btn {
    width: 100px;
    height: 100px;
    background-color: #fbfdff;
    border: dashed 1px #c0ccda;
    border-radius: 5px;
    i {
      font-size: 30px;
      margin-top: 20px;
    }
    &-text {
      margin-top: -10px;
    }
  }
  .avatar {
    cursor: pointer;
  }
}
.team_name_list {
  width: 100%;
  span {
    display: flex;
    width: 100%;
    padding: 5px 10px;
    cursor: pointer;
  }
  span:hover {
    color: #1890ff;
  }
}
</style>
