<template>
  <div id="create-customer"  class="ls-vertical">
    <navbar icon="back" title="我的客户" ></navbar>
    <div class="ls-container"  >
      <step-node  ref="stepNodeRef"  :curr-step="currStep" ></step-node>
    <el-collapse-transition>
      <div  class="main-content">
        <div class="top">{{currStep}}.{{stepTitle}}</div>
        <el-form v-show="currStep===1" :model="formData"  class="form-box"  ref="formRef"
            label-position="left"  label-width="100px" size="mini" >
          <!--1. 创建客户 -->
          <module-form
            v-if="currStep==1"
            :formdata.sync='formData'
            :datalist="simpleList"
            toptitle="基础信息"
            :fileTypeList="['jpg', 'jpeg', 'png', 'gif']"
          >
            <template v-slot:header>
              <el-col :span="6">
                <el-form-item label="客户名称"  prop="customerName"
                  :rules="[{ required: true, message: '请输入',  trigger:  'blur' } ]" >
                  <el-input  v-model="formData.customerName"
                    v-inputFilter:trim
                    placeholder="请输入">
                    <i class="el-icon-search"  slot="suffix"
                      @click="handleCustomer">
                    </i>
                  </el-input>
                </el-form-item>
              </el-col>
            </template>
          </module-form>
          <el-form  :model="contactForm"   ref="contformRef"
            label-position="left"  label-width="100px" size="mini" >
            <module-form
              :formdata.sync='contactForm'
              :datalist="contactList"
              modelId="3114"
              modelName="CM_CONTACT"
              toptitle="联系人信息"
              :fileTypeList="['jpg', 'jpeg', 'png', 'gif']"
            >
            </module-form>
          </el-form>
          <el-form  :model="followForm"   ref="followFormRef"
            label-position="left"  label-width="100px" size="mini" >
            <module-form
              :formdata.sync='followForm'
              :datalist="followUserList"
              toptitle="主跟进人员"
              :generateField="true"
              @generate="handleGenerate"
              ref="followRef"
            >
            </module-form>
          </el-form>
        </el-form>
        <!--2. 完善详细信息 -->
        <div v-show="currStep===2">
          <detail-info
            ref="detailInfoRef">
          </detail-info>
          <document-info
            :customerType="customerType"
            ref="docInfoRef" >
          </document-info>
        </div>
       <!--3. 地址业务信息 -->
       <address-bus-info
          v-show="currStep===3 && customerType !=='potential'"
          :cmContact="cmContact"
          ref="addressBusRef"
        >
       </address-bus-info>
       <!--4. 客户评估 -->
       <el-form v-show="currStep===4"
          :model="evalForm"  ref="evalFormRef"
          class="form-box" label-position="left"
          label-width="110px" size="mini" >
          <module-form
            :formdata.sync='evalForm'
            :datalist="evaluatInfoList"
            toptitle="客户评估"
          >
          </module-form>
        </el-form>
        <div  class="footer-btn">
          <el-button v-show="currStep > 1 "
           @click="handlePrevious"
           type="primary"  size="mini" >上一步</el-button>
          <el-button v-show="showNextBtn"
           @click="handleNext"
           type="primary"  size="mini" >下一步</el-button>
          <el-button  v-show="showAgentBtn && !processId"
            @click="creatCustomer('potential')"
            type="warning"  size="mini" >报备至代理商</el-button>
          <el-button   v-show="currStep==4 && !processId"
            @click="handleApply"
            type="warning"  size="mini" >提交申请</el-button>
          <el-button v-show="showSaveBtn"
            @click="temporarySave"
            type="primary"  size="mini" >保存</el-button>
        </div>
      </div>
    </el-collapse-transition>
      <approval-comment ref="approve" @apply="temporarySave" :moduleId="this.moduleId" v-if="processId"/>
      <approval-log ref="log" v-if="processId"/>
    </div>
    <dig-cm ref="digCmRef"></dig-cm>
  </div>
</template>

<script>

  import stepNode from './components/step-node.vue'
  import digCm from './components/dig-cm.vue'
  import moduleForm  from '@/pages/customer/public/components/module-form.vue'
  import followUser  from '@/pages/customer/public/components/follow-user.vue'
  import detailInfo from './components/detail-info.vue'
  import addressBusInfo from './components/address-bus-info.vue'
  import documentInfo from './components/document-info.vue'
  export default{
    name: 'create-customer',
    components:{
      stepNode,
      digCm,
      moduleForm,
      followUser,
      detailInfo,
      addressBusInfo,
      documentInfo,
    },
    provide(){
      return{}
    },
    created(){

      this.id = this.$route.query.id||this.$common.getUrlParams('bid');
      this.processId=this.$common.getUrlParams('processId');

      this.initData();
    },
    mounted(){

    },
    methods:{
      async initData(){
        let simpleModulePro = this.initTemplateData('KHXXTJBJ_3110', '基础信息', 'simple');
        let contactModulePro = this.initTemplateData('KHLXRTJBJ_3114', '联系人', 'add');
        let followModulePro = this.initTemplateData('KHGJRYTJBJ_3112', '跟进人员', 'add');
        if(this.id){
          this.formData  = await  this.getByIdCmInfo() || {};
          this.contactForm = JSON.parse(JSON.stringify(this.formData.cmContact)) || {};
          let cmFollowList = this.formData.cmFollowList || [];
          for(let i=0; i<cmFollowList.length; i++){
            let item = cmFollowList[i];
            if(item.whetherMain == 'Y'){
              this.followForm = item;
              break
            }
          }
        }else{
          this.contactForm.whetherConsignee = 'Y'; //默认收货联系人
          this.followForm.whetherMain = 'Y'; //主跟进
        }

        let data = await simpleModulePro;
        for(let i=0; i< data.length; i++){
          if(data[i].fieldAttr == "customerName" ){
            data.splice(i, 1);
            break;
          }
        }
        this.simpleList = data;
        this.contactList = await contactModulePro;
        this.followUserList = await followModulePro;

        if(this.followForm && this.followForm.companyId){
          for(let i=0; i<this.followUserList.length; i++){
            let item = this.followUserList[i];
            if(item.fieldAttr == 'deptName'){
              let o = {
                companyId: this.followForm.companyId
              }
              this.$set(item, 'parentObj', o);
              break;
            }
          }
        }

      },
      initTemplateData(id, tempType, opType){
        return new Promise((resolve, reject)=>{
           let param = {
             templateId: id,
             templateType: tempType,
             operationType: opType,
             status: 'Y',
           };
           this.$ajax.post({
             domain: 'crmCmUrl',
             url: 'templates.queryByTemplateIdList',
             data: param,
             requestType: 'body',
             showLoad: true,
             success: function (res) {
              if (res.errorCode === 200) {
                let data = res.data || [];
                resolve(data);
              }
             }.bind(this),
             error: function (res) {
               this.$message.error( res.body.msg || res.msg);
               reject(res);
             }.bind(this)
           })
         }).catch((err)=>{
           console.log(err.data);
        })
      },
      getByIdCmInfo(){
        let contactId = this.formData.cmContact ? this.formData.cmContact.id : '';
        return new Promise((resolve, reject) =>{
          this.$ajax.post({
            domain: 'crmCmUrl',
            url: 'cmInfo.getByIdCmInfo',
            data: {
              id: this.id,
              contactId
            },
            requestType: 'body',
            showLoad: true,
            success: function (res) {
              if (res.errorCode === 200) {
                let data = res.data || {};
                resolve(data);
              }
            }.bind(this),
            error: function (res) {
              this.$message.error( res.body.msg || res.msg);
              reject(res);
            }.bind(this)
          })
        }).catch(err=>{
          console.log(err);
        })
      },
      handleCustomer(){
        this.$refs.digCmRef.visible = true;
      },
      getCmEvalInfo(){
        this.$ajax.post({
          domain: 'crmCmUrl',
          url: 'cmEval.getCmEvalInfo',
          data: {customerId: this.id},
          requestType: 'body',
          showLoad: true,
          success: async function (res) {
            if (res.errorCode === 200) {
              let data = res.data || {};
              this.evalForm = Object.assign(data, this.evalForm);
              this.evaluatInfoList = await this.initTemplateData('KHPGTJBJ_3113', '客户评估', 'add');
            }
          }.bind(this),
          error: function (res) {
            this.$message.error( res.body.msg || res.msg);
          }.bind(this)
        })
      },
      //创建客户，报备至代理商
      creatCustomer(flag){
        this.isTemporarySave = false; 
        this.customerType = flag;
        this.$refs.detailInfoRef.handleSave();
      },
      handleNext(){
        this.isTemporarySave = false;
        this.customerType = 'formal';
        if(this.currStep === 1 ){
          let cci = this.formData.customerClassifyId;
          if( cci == 'busCustomer' ||
              cci == 'ternimalCustomer' ||
              cci == 'franchisedDealer'){
            this.showNextBtn = false;
          }
          this.handleSaveCmInfo();
        }else if(this.currStep === 2 ){
          let cci = this.$refs.detailInfoRef.formData.customerClassifyId;
          //下一步必须为代理商、直接客户、内部客户
          if(!(cci =='NBCustomer' || cci=='dirctCustomer' || cci=='agent')){
            this.$message('申请正式客户客户属性必须为“直接客户、代理商、内部客户”!' );
            return;
          }
          this.$refs.detailInfoRef.handleSave();
        } else if(this.currStep === 3 ){
          this.$refs.addressBusRef.handleSave();
        } else {

        }

      },
      handlePrevious(){
        if(this.currStep == 2){
          this.initData();
          this.showAgentBtn = false;
          this.customerType = 'formal';
        }
        this.currStep -= 1;
        this.showNextBtn = true;

      },
      //暂时保存
      temporarySave(){
        this.isTemporarySave = true;
        this.customerType = 'formal';
        switch(this.currStep){
          case 1:
            this.customerType = 'business';//第一步保存为商机客户
            this.handleSaveCmInfo();
            break;
          case 2:
            this.$refs.detailInfoRef.handleSave();
            break;
          case 3:
            this.$refs.addressBusRef.handleSave();
            break;
          case 4:
            this.handleSaveEval();
            break;
        }

      },
      handleGenerate(val, obj, select, list){
        if(obj.fieldAttr == 'companyName' ){
          this.followForm.companyId = select.vaule;
          this.followForm.companyName = val;
          this.$refs.followRef.moduleForm.deptName = '';
          for(let i=0; i<this.followUserList.length; i++){
            let item = this.followUserList[i];
            if(item.fieldAttr == 'deptName'){
              let o = {
                companyId: select.vaule
              }
              this.$set(item, 'parentObj', o);
              break;
            }
          }
        }
      },
      //保存 简化客户信息
      handleSaveCmInfo() {
        this.$refs['formRef'].validate((valid) => {
          if (!valid) return;
            this.$refs['contformRef'].validate((valid) => {
              if (!valid) return;
              this.$refs['followFormRef'].validate((valid) => {
              if (!valid) return;
                let param =  JSON.parse(JSON.stringify(this.formData));
                param.cmFollow = this.followForm;
                param.cmContact = this.contactForm;
                param.cmContact.defaultData = 'Y';
                if(this.customerType == 'business'){//创建商机客户
                  param.approveStatus ='filed';
                }
                if(this.id){
                 param.cmFollow.customerId = param.cmContact.customerId = this.id;
                }
                this.$ajax.post({
                domain: 'crmCmUrl',
                url: 'cmInfo.saveOrUpdateCmInfo',
                data: param,
                requestType: 'body',
                showLoad: true,
                success: function (res) {
                  if (res.errorCode === 200) {
                    this.$message({
                      type: 'success',
                      duration: 1250,
                      message: '保存成功',
                      showClose: true
                    });
                    let data = res.data;
                    this.formData = Object.assign({},this.formData ,data);
                    this.id = data.id;
                    this.showSaveBtn = true;
                    this.cmContact = JSON.parse(JSON.stringify(data.cmContact));
                    this.formData.groupType = data.cmContact.groupType;
                    if(this.customerType == 'business'){
                      this.$router.push("customerList");
                      return;
                    };
                    this.$refs.detailInfoRef.cmInfo = this.formData;
                    this.$refs.detailInfoRef.initData();
                    this.$refs.docInfoRef.cmInfo = this.formData;
                    this.$refs.docInfoRef.initFileList();
                    this.currStep++;
                    let cci = this.formData.customerClassifyId;
                    if(cci=='ternimalCustomer' || cci=='franchisedDealer'){
                      this.showAgentBtn = true;
                    }else {
                      this.showAgentBtn = false;
                    }
                  }
                }.bind(this),
                error: function (res) {
                  this.$message.error( res.body.msg || res.msg);
                }.bind(this)
              })
            })
          })
        })
      },
      checkFile(){
        let check = true;
        let data = this.$refs.docInfoRef.fileTableData
        for(let i=0; i<data.length; i++){
          let item = data[i];
          if(item.required && !item.fileId){
            check = false;
            this.$message("请先上传必须文件！");
            break;
          }
        }
        return check;
      },
      //保存客户评估
      handleSaveEval(flag){
        return new Promise((resolve, reject)=>{
          this.$refs['evalFormRef'].validate((valid) => {
            if (!valid) return;
            let param =  JSON.parse(JSON.stringify(this.evalForm));
            param.customerId = this.id;
            this.$ajax.post({
              domain: 'crmCmUrl',
              url: 'cmEval.saveOrUpdateCmEval',
              data: param,
              requestType: 'body',
              showLoad: true,
              success: function (res) {
                if (res.errorCode === 200) {
                  !flag && this.$message({
                             type: 'success',
                             duration: 1250,
                             message: '保存成功',
                             showClose: true
                           });
                  resolve(res);
                }
              }.bind(this),
              error: function (res) {
                this.$message.error( res.body.msg || res.msg);
                reject(res);
              }.bind(this)
            })
          });
        }).catch(err=>{
          console.log(err);
        })

      },
      //正式客户申请
      async handleApply(){
        let result = await this.handleSaveEval('apply');
        if(!result.success){
          return;
        }
        this.$confirm('确定提交?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then( async () => {

           this.doSubmit();

        }).catch(() => { });
      },
      doSubmit(){
        let startType = 'Customer_Erp_Apply';

        // if(this.customerType === 'formal'){
        //   startType = 'Customer_Erp_Apply';
        // }else{
        //   startType = 'Customer_Potential_Apply';
        // };
        //解决修改客户归属导致的问题
        this.$ajax.post({
          domain: 'crmCmUrl',
          url: 'cmProcess.doSubmit',
          data: {
            busId: this.id,
            startType: startType,
            moduleId: this.moduleId
          },
          requestType: 'body',
          showLoad: true,
          success: function (res) {
            if (res.errorCode === 200) {
              this.$message({
                type: 'success',
                duration: 1250,
                message: '申请流程提交成功',
                showClose: true
              });
              this.$router.push('customerList');
            }
          }.bind(this),
          error: function (res) {
            this.$message.error( res.body.msg || res.msg);
          }.bind(this)
        })
      },

    },
    data(){
      return {
        stepTitle: '创建客户', //步骤标题
        currStep: 1,//当前所处步骤
        showNextBtn: true, //显示下一步按钮
        moduleId:'3110',
        showAgentBtn: false,
        showSaveBtn: true,//显示保存按钮
        customerType: 'formal', //客户类型，默认新建正式客户
        isTemporarySave: false, //是否暂时保存
        id: '', //主键Id
        formData: {},
        contactForm: {},
        cmContact: {},
        followForm: {},
        evalForm: {},

        simpleList: [],
        contactList: [],
        followUserList: [],
        evaluatInfoList: [],

      }
    }
  }
</script>

<style lang="scss"  lang="scss">
@import './scss/create.scss';

</style>
