<template>
  <div class="ls-vertical">
    <navbar icon="back"  title="送样申请" :back-func="backCallBack" :buttons="btns" @clickbutton="clickbtn" ></navbar>
    <div class="ls-container ls-project" >
      <!-- 基础信息 -->
      <el-form  :model="paramForm" :rules="rules"  ref="formRef" class="main-info"  label-width="125px" size="mini"  >
        <div class="tampalte-contain" >
          <div class="main-title">基础信息</div>
          <el-row class="info-box">
            <el-col :span="6">
               <el-form-item label="申请编号" label-width="100px" >
                 <el-input v-model="paramForm.sampleCode" disabled  placeholder="自动带出" />
               </el-form-item>
               <el-form-item label="销售人员" prop="salesNameAry" label-width="100px">
                  <aws-org  v-model="paramForm.salesNameAry"
                    :editable="disabledForm||false?false:true"
                    :sid="sid" :ismuti="false"  ref="awsOrgSaleRef">
                  </aws-org>
               </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="客户名称"   prop="customer" label-width="100px">
                <el-input v-model="paramForm.customer"
                    :disabled="baseInfo.customer||paramForm.status!='draft'||flag?true:false"
                    @focus="dialogCustomeInfo"  readonly placeholder="请选择">
                   <i v-if="!baseInfo.customer && paramForm.status=='draft' && !disabledForm " slot="suffix"
                    @click="dialogCustomeInfo" class="el-input__icon el-icon-arrow-down"></i>
                </el-input>
              </el-form-item>
              <el-form-item label="商务人员" prop="assistantNameAry" label-width="100px">
                <aws-org  v-model="paramForm.assistantNameAry"
                    :editable="disabledForm||false?false:true"
                    :ismuti="false" :sid="sid"  ref="assistantRef">
                </aws-org>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="代理商"  prop="agentName"
               :rules="[ { required: paramForm.customerType=='终端客户'?true:false, message: '请选择', trigger: 'change' }]"
              >
                <el-select v-model="paramForm.agentName"   @change="agentChange"
                           :disabled="disabledForm"
                  placeholder="请选择"  clearable >
                 <el-option
                         v-for="item in agentCustomerList"
                         :key="item.customerFullName"
                         :label="item.customerFullName"
                         :value="item.customerFullName">
                 </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="期望送样日期" prop='expectDate' >
                <el-date-picker
                      v-model="paramForm.expectDate"
                      type="date"
                      :disabled="disabledForm"
                      :editable="false"
                      :picker-options="pickerOptions"
                      format="yyyy-MM-dd"
                      value-format="yyyy-MM-dd"
                      placeholder="请选择"
                     >
                </el-date-picker>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="项目编码" prop="projectCode" >
                <el-select v-model="paramForm.projectCode"  @change="projectCodeChange"
                  placeholder="请选择"  clearable :disabled="disabledForm">
                  <el-option  v-for="(item,index) in projectCodeList"
                      :key="item.projectCode"
                      :value="item.projectCode"
                      :label="item.projectCode"
                      >
                  </el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="是否收费" prop="chargeSample" >
                <el-select v-model="paramForm.chargeSample"  @change="isChargeChange" :disabled="disabledForm"
                    placeholder="请选择" filterable clearable >
                   <el-option
                     v-for="item in freeList"
                     :key="item.key"
                     :label="item.key"
                     :value="item.vaule">
                   </el-option>
                 </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="24">
              <el-row>
                <el-col :span="6">
                  <el-form-item label="收费方式" prop="settleCharge" label-width="100px">
                    <el-select v-model="paramForm.settleCharge" @change="freeSetChange" :disabled="disabledForm"
                        placeholder="请选择" filterable clearable >
                       <el-option
                         v-for="item in freeSettlementList"
                         :key="item.key"
                         :label="item.key"
                         :value="item.ext1">
                       </el-option>
                     </el-select>
                  </el-form-item>
                </el-col>
                <el-col :span="18" >
                   <el-form-item label="知会人" label-width="100px" >
                     <aws-org  v-model="paramForm.informerParamList"
                         :editable="disabledForm||false?false:true"
                        :sid="sid"  ref="orgInfoRef">
                     </aws-org>
                   </el-form-item>
                </el-col>
              </el-row>
            </el-col>
            <el-col :span="24">
                <el-form-item label="备注说明" prop="remark" label-width="100px">
                    <el-input v-model="paramForm.remarks"
                      type="textarea"
                      :autosize="{ minRows: 1, maxRows: 3}"
                      maxlength="500"
                      show-word-limit
                      placeholder="1.资源料号（如有） 2.其他说明" />
                </el-form-item>
             </el-col>
          </el-row>
        </div>
        <div class="tampalte-contain" >
          <div class="main-title">物流要求</div>
          <el-row class="info-box">
            <el-col :span="6">
              <el-form-item label="联系人" prop="personContact" label-width="100px">
                <el-input v-model="paramForm.personContact" :disabled="disabledForm"
                  maxlength="50"
                  show-word-limit
                  placeholder="请输入" />
              </el-form-item>
            </el-col>
            <el-col :span="6" >
              <el-form-item label="联系电话" prop="phone" label-width="100px">
               <el-input v-model.trim="paramForm.phone"  placeholder="请输入" :disabled="disabledForm" />
              </el-form-item>
            </el-col>
            <el-col :span="24">
                <el-form-item label="送样地址"  prop="sampleAddr" label-width="100px">
                    <el-input v-model="paramForm.sampleAddr" :disabled="disabledForm"
                      type="textarea"
                      :autosize="{ minRows: 1, maxRows: 3}"
                      maxlength="100"
                      show-word-limit
                      placeholder="请输入" />
                </el-form-item>
             </el-col>
          </el-row>
        </div>
        <div class="tampalte-contain" >
          <div class="main-title">上传附件</div>
          <el-form-item label="选择文件"  label-width="100px" style="margin-top: 10px;">

            <ls-upload  v-model="paramForm.filesList"
              :showuploadbtn="disabledForm?false:true"
              :showdeletebtn="disabledForm?false:true"
              ref="lsUploadRef" >
            </ls-upload>
          </el-form-item>
        </div>

        <div class="tampalte-contain" >
          <div class="main-title">送样要求</div>
          <el-button v-if="!disabledForm" @click="addRow"   type="text" class="add-btn"  icon="el-icon-plus"  >添加行</el-button>
            <el-row    v-for="(item,index) in paramForm.sampleLineParamList " :key="index"  class="info-box" >
              <template :disabled="disabledForm">
              <el-button  v-if="!disabledForm"  @click="deleteRow(index)"   type="text" class="delete-btn"  icon="el-icon-delete"  >删除行</el-button>
              <el-col :span="6">
                <el-form-item label="子行编码" :prop="'sampleLineParamList.' + index + '.projectLineCode' "
                  :rules="{ required: true, message: '请选择', trigger: 'change' }" label-width="100px" >
                  <el-input v-model="item.projectLineCode"  readonly :disabled="disabledForm"
                      @focus="showDigLineCode(index)"  placeholder="请选择">
                     <i v-if="!disabledForm" slot="suffix"
                     @click="showDigLineCode(index)" class="el-input__icon el-icon-arrow-down"></i>
                  </el-input>
                </el-form-item>
                <el-form-item label="芯片型号" :prop="'sampleLineParamList.' + index + '.chipModel' "
                  :rules="{ required: true, message: '不能为空', trigger: 'change' }" label-width="100px" >
                  <!-- <el-input v-model="item.chipModel"   disabled placeholder="请输入" /> -->
                  <el-select v-model="item.chipModel"
                       placeholder="请选择" filterable clearable disabled >
                     <el-option
                       v-for="(item, i) in chipModelList"
                       :key="i"
                       :label="item.key"
                       :value="item.ext1">
                     </el-option>
                   </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="细分领域"  :prop="'sampleLineParamList.' + index + '.industrySegmentation' "
                  :rules="{ required: true, message: '不能为空', trigger: 'change' }" label-width="100px" >
                  <el-input v-model="item.industrySegmentation" disabled  placeholder="根据子行编码带出" />
                </el-form-item>
                <el-form-item label="锁定FW" :prop="'sampleLineParamList.' + index + '.lockFw' "
                  :rules="{ required: true, message: '不能为空', trigger: 'change' }" label-width="100px" >
                  <el-select v-model="item.lockFw" placeholder="根据子行编码带出" disabled  >
                    <el-option
                            v-for="item in lockFwList"
                            :key="item.value"
                            :label="item.label"
                            :value="item.value">
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="PN" :prop="'sampleLineParamList.' + index + '.longsysPN' "
                  :rules="{ required: true, message: '不能为空', trigger: 'change' }" >
                  <el-input v-model="item.longsysPN" disabled   placeholder="根据子行编码带出" />
                </el-form-item>
                <el-form-item label="需要测报" :prop="'sampleLineParamList.' + index + '.needForecast' "
                  :rules="{ required: true, message: '请选择', trigger: 'change' }"  >
                  <el-select v-model="item.needForecast" :disabled="disabledForm"
                   placeholder="请选择"  clearable >
                   <el-option  v-for="(item,index) in testReportList"
                      :key="item.value"
                      :value="item.value"
                      :label="item.label"
                      >
                   </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="6">
                <el-form-item label="芯片平台" :prop="'sampleLineParamList.' + index + '.platform' "
                  :rules="{ required: true, message: '不能为空', trigger: 'change' }">
                  <!-- <el-input v-model="item.platform"   disabled placeholder="请输入" /> -->
                  <common-select v-model="item.platform" disabled dictType="Crm_Application_Chip_Platform" >
                  </common-select>
                </el-form-item>
                <el-form-item label="样品承认书"  :prop="'sampleLineParamList.' + index + '.needSample' "
                  :rules="{ required: true, message: '请选择', trigger: 'change' }" >
                  <el-select v-model="item.needSample" :disabled="disabledForm"
                     placeholder="请选择"  clearable >
                    <el-option  v-for="(item,index) in admitList"
                        :key="item.value"
                        :value="item.value"
                        :label="item.label"
                        >
                    </el-option>
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :span="24" >
                <el-row>
                  <el-col :span="6">
                    <el-form-item label="申请数量"  :prop="'sampleLineParamList.' + index + '.applyQuantity' "
                      :rules="{ required: true, message: '请输入', trigger: 'blur' }" label-width="100px" >
                      <el-input v-model="item.applyQuantity"  v-input-filter:gzero :disabled="disabledForm"
                        @blur="applyQuantityBlur(item.applyQuantity,  index)" placeholder="请输入" />
                      <p class="position-p">(pcs)</p>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                    <el-form-item label="样品用途"  :prop="'sampleLineParamList.' + index + '.samplePurpose' "
                      :rules="{ required: true, message: '请选择', trigger: 'change' }" label-width="100px" >
                      <common-select v-model="item.samplePurpose"
                        dictType="Crm_Sample_Use" :disabled="disabledForm"
                        :ismult="true" :iscollapse="true" >
                      </common-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="6">
                  <el-form-item label="产品等级" :prop="'sampleLineParamList.' + index + '.itemLevel' ">
                    <el-input v-model="item.itemLevel" disabled   placeholder="根据子行编码带出" />
                  </el-form-item>
                  </el-col>
                </el-row>
              </el-col>
              <el-col :span="24">
                <el-form-item label="客制要求" label-width="100px">
                  <el-input v-model="item.custRequired" :disabled="disabledForm"
                            type="textarea"
                            :autosize="{ minRows: 1, maxRows: 3}"
                            :class=" item.custRequired&&flag?'red':'' "
                            maxlength="500"
                            show-word-limit
                            placeholder="请输入" />
                </el-form-item>
              </el-col>
              </template>
              <template  v-if="flag=='item'">
                <el-col :span="6">
                  <el-form size="mini" >
                    <el-form-item  label="样品状态"  :prop="'sampleLineParamList.' + index + '.sampleStatus' "
                      :rules="{ required: true, message: '请选择', trigger: 'blur' }"  label-width="100px"  >
                      <common-select v-model="item.sampleStatus"
                        :disabled="item.sealSample=='Y'?true:false"
                        dictType="Crm_Sample_Status"  >
                      </common-select>
                    </el-form-item>
                  </el-form>
                  <el-form-item label="FW版本"  label-width="100px" >
                    <el-input v-model="item.fwVersion" disabled    placeholder="请输入" />
                  </el-form-item>
                  <el-form-item label="样品验证结果"   :prop="'sampleLineParamList.' + index + '.checkResult' "
                  :rules="{ required: true, message: '请选择', trigger: 'change' }"  label-width="100px" >
                    <el-select v-model="item.checkResult"     :disabled="item.sealSample=='Y'?true:false"
                       placeholder="请选择"  clearable >
                      <el-option  v-for="(item,index) in sampleResultList"
                          :key="item.value"
                          :value="item.value"
                          :label="item.label"
                          >
                      </el-option>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="小批试产时间"  label-width="100px" >
                    <el-date-picker
                      v-model="item.trialDate"
                      :disabled="item.sealSample=='Y'?true:false"
                      @change="trialTimeChange(item.trialDate, index)"
                      type="date"
                      :editable="false"
                      format="yyyy-MM-dd"
                      value-format="yyyy-MM-dd"
                      placeholder="请选择"
                     >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item  label="样品数量"  label-width="100px" >
                    <el-input v-model="item.sampleQuantity" disabled    placeholder="请输入"/>
                  </el-form-item>
                  <el-form-item label="产品PN"  label-width="100px" >
                    <el-input v-model="item.productPN" disabled    placeholder="请输入" />
                  </el-form-item>
                  <el-form-item label="小批试产数量"  label-width="100px" >
                    <el-input v-model="item.trialQuantity"  v-input-filter:gzero
                      v-input-filter:comdify    placeholder="请输入"    :disabled="item.sealSample=='Y'?true:false"/>
                    <p class="position-p">(pcs)</p>
                  </el-form-item>
                  <el-form-item label="实际量产时间"  label-width="100px" >
                    <el-date-picker
                      v-model="item.outputDate"
                      :disabled="item.sealSample=='Y'?true:false"
                      @change="outputTimeChange(item.outputDate, index)"
                      type="date"
                      :editable="false"
                      format="yyyy-MM-dd"
                      value-format="yyyy-MM-dd"
                      placeholder="请选择"
                     >
                    </el-date-picker>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item  label="料号"   >
                    <el-input v-model="item.num" disabled    placeholder="请输入" />
                  </el-form-item>
                  <el-form-item label="产品类别"   >
                    <el-input v-model="item.projectType" disabled    placeholder="请输入" />
                  </el-form-item>
                  <el-form-item label="承认样品时间"  >
                    <el-date-picker
                      v-model="item.recDate"
                      :disabled="item.sealSample=='Y'?true:false"
                      @change="recTimeChange(item.recDate, index)"
                      type="date"
                      :editable="false"
                      format="yyyy-MM-dd"
                      value-format="yyyy-MM-dd"
                      placeholder="请选择"
                     >
                    </el-date-picker>
                  </el-form-item>
                  <el-form-item label="量产数量"   >
                    <el-input v-model="item.outputQuantity"     :disabled="item.sealSample=='Y'?true:false"
                      v-input-filter:gzero
                      v-input-filter:comdify
                      placeholder="请输入" />
                    <p class="position-p">(pcs)</p>
                  </el-form-item>
                </el-col>
                <el-col :span="6">
                  <el-form-item label="容量"   >
                    <el-input v-model="item.capacity" disabled    placeholder="请输入" />
                  </el-form-item>
                  <el-form-item label="批次号"   >
                    <el-input  disabled    placeholder="请输入" />
                  </el-form-item>
                  <el-form-item label="实际送样时间"  >
                    <el-date-picker
                      v-model="item.actualDate"
                      :disabled="item.sealSample=='Y'?true:false"
                      @change="actualTimeChange(item.actualDate, index)"
                      type="date"
                      :editable="false"
                      format="yyyy-MM-dd"
                      value-format="yyyy-MM-dd"
                      placeholder="请选择"
                     >
                    </el-date-picker>
                  </el-form-item>

                </el-col>
                <el-col :span="24" >
                  <el-form-item label="补充说明" label-width="100px">
                    <el-input v-model="item.remark"    :disabled="item.sealSample=='Y'?true:false"
                      type="textarea"
                      :autosize="{ minRows: 1, maxRows: 3}"
                      maxlength="500"
                      show-word-limit
                      placeholder="请输入" />
                  </el-form-item>
                </el-col>
              </template>
            </el-row>
        </div>

      </el-form>

      <dialog-customer
           @setCustValue="getCustInfo"
           ref="digCustomRef" :notStatusList="['F','H']">
      </dialog-customer>
      <dialog-line-code  ref="digLineCodeRef" :project-id="paramForm.projectId" @setLineInfo="setLineInfo" />
      <comment-logs ref="approve" v-if="processId" :isComment="true" :isApploval="true" :taskDefId.sync="taskRefId" :processId.sync="processId"/>
      <div style="height: 300px">
        <log-table  ref="proceLogTableRef" v-if="!processId && paramForm.status!='draft' && !isChange" :busId.sync="sampleId"></log-table>
      </div>

    </div>
  </div>
</template>

<script>
import dialogLineCode from './components/dialog/dialog-lineCode.vue';
import commonSelect from '@/common/commonSelectList.js'
export default {
  name: 'sample-apply',
  components:{
    dialogLineCode,
  },
  created(){
    let $this=this;
    parent.window.doSubmit = function(param){
      if(!$this.isProccess){
        $this.approve(param);
        return false;
      }else{
        return true;
      }
    };
    this.getSelectList();
    this.rowId = this.$route.params.id || this.$common.getUrlParams('id');
    //流程相关
    this.sampleId= this.$common.getUrlParams('bid');
    this.processId=this.$common.getUrlParams('processId');
    this.taskRefId=this.$common.getUrlParams('taskRefId');
    this.isChange = this.$route.params.isChange || this.$common.getUrlParams('isChange');
    debugger;
    this.flag = this.$route.params.flag || this.$common.getUrlParams('flag');
    this.backRouteUrl = this.$route.params.backRouteUrl || this.$common.getUrlParams('backRouteUrl');
    this.disabledForm = this.$route.params.disabledForm || this.$common.getUrlParams('disabledForm') == 'true' ? true : false || false;
    // if(this.disabledForm){
    //   this.btns.splice(1, 2);
    //   this.btns[0].btnEvent = 'update';
    //   this.btns[0].show = this.flag == 'line'?false:true;
    // }
    this.initDate();
  },
  mounted(){},
  methods:{
    approve(param){
      if(!this.$refs.approve.valid(param)){
        return;
      }
      //提交之前先保存
      //if(param.actionName=='提交' && param.taskRefId=='obj_c9d35176286000016ae11a021250139a'){
      this.saveForm('processId');
      //}

      param = Object.assign(param,this.$refs.approve.processForm);
      this.$ajax.post({
        domain: 'crmUrl',
        url: 'sample.approve',
        data: param,
        requestType: 'body',
        showLoad: true,
        success: function (res) {
          if (res.errorCode === 200) {
            this.isProccess=true;
            parent.FormToolBarAction.BTN_TRANSACT();
          }else {
            this.$message.error(res.msg)
          }
        }.bind(this),
        error: function (res) {
          this.$message({
            type: 'error',
            message: res.body.msg || res.msg
          })
        }.bind(this)
      });
    },
    initDate(){
      this.baseInfo = this.$route.params.baseInfo || {};
      this.productRow = this.$route.params.productRow || [];

      if(this.baseInfo && this.baseInfo.projectCode){
        this.paramForm.customer = this.baseInfo.customer;
        this.paramForm.customerId = this.baseInfo.customerId;
        this.paramForm.agentName = this.baseInfo.agentName;
        this.paramForm.agentId = this.baseInfo.agentId;
        this.paramForm.projectCode = this.baseInfo.projectCode;
        this.paramForm.projectId = this.baseInfo.id;
        this.paramForm.salesNameAry.push({uid: this.baseInfo.salesId, name: this.baseInfo.salesName});
      }
      if(this.productRow.length){ //产品行，新增样品
        this.paramForm.sampleLineParamList = [];
        let sampleLineParam = [];
        this.productRow.forEach((item, index)=>{
          sampleLineParam.push(JSON.parse(JSON.stringify(this.sampleLineParamObj)));
          sampleLineParam[index].projectLineCode = item.lineCode||'';
          sampleLineParam[index].projectLineId = item.id;
          sampleLineParam[index].longsysPN = item.productPn || '';
          sampleLineParam[index].lockFw = item.lockFw || '';
          sampleLineParam[index].industrySegmentation = this.baseInfo.industrySegmentation;
          sampleLineParam[index].platform = this.baseInfo.platform;
          sampleLineParam[index].chipModel = this.baseInfo.chipModel;
        })
        this.paramForm.sampleLineParamList = sampleLineParam;
      } else if((this.rowId || this.sampleId) && this.flag){
        this.getBySampleFlagAndId(this.flag, this.rowId,this.sampleId);
      } else {
        this.paramForm.sampleLineParamList.push(JSON.parse(JSON.stringify(this.sampleLineParamObj)));
      }
    },
    //弹窗选择客户信息 弹窗
    dialogCustomeInfo(){
      this.$refs.digCustomRef.visible = true;
    },
    //根据客户弹窗选择的行数据，获取与客户相关信息
    getCustInfo(row){
      this.paramForm.customer = row.customerFullName;
      this.paramForm.customerId = row.customerNo;
      this.paramForm.customerType = row.customerType;
      this.paramForm.agentName = '';
      this.paramForm.agentId = '';
      this.getAgentCustomerList(row.customerNo); //查代理商
      this.paramForm.projectCode = '';
      this.paramForm.projectId = '';
      //根据选择的客户编号，带出 主业务，主商务人员
      if(row.salesUserName && row.salesName){
        this.$refs.awsOrgSaleRef.reset([{uid: row.salesUserName, name: row.salesName }]);
      }
      if(row.aidUserName && row.aidName){
        this.$refs.assistantRef.reset([{uid: row.aidUserName, name: row.aidName }]);
      }
      if(this.baseInfo && !this.baseInfo.projectCode){
        this.getProjectCode();
      }
      this.paramForm.sampleLineParamList.forEach(item=>{
        item.projectLineCode = '';
        item.projectLineId = '';
        item.industrySegmentation = '';
        item.longsysPN = '';
        item.platform = '';
        item.chipModel = '';
        item.lockFw = '';
      })
    },
    //根据选择的客户编号，带出 代理商数据
    getAgentCustomerList(customerNo){
        let param = {
          busSystem: 'cloud-crm-project',
          currPage: 1,
          pageSize: 999,
          customerNo: customerNo,
        }
        this.$ajax.get({
            domain: 'dataQueryUrl',
            url: 'bus.getAgentCustomers',
            data: param,
            requestType: 'form',
            showLoad: true,
            success: function (res) {
                if (res.errorCode === 200) {
                    this.agentCustomerList = res.data.list || [];
                    if(this.agentCustomerList.length ===1){
                      this.paramForm.agentName = this.agentCustomerList[0].customerFullName;
                      this.paramForm.agentId = this.agentCustomerList[0].customerNo;
                    }
                }
            }.bind(this),
            error: function (res) {
              this.$message({
                type: 'error',
                message: res.body.msg || res.msg
              })
            }.bind(this)
        })
    },

    //代理商 select change
    agentChange(name){
        this.agentCustomerList.forEach(item=>{
          if(item.customerFullName === name){
            this.paramForm.agentId = item.customerNo;
          }
        })
    },
    //根据客户，代理商 ，带出已审批状态的 项目编码
    getProjectCode() {
      let projectParam = {
        currPage: 1,
        pageSize: 999,
        projectStatus: 'audited',
        customer: this.paramForm.customer,
      };
      this.$ajax.post({
        domain: 'crmUrl',
        url: 'project.findBasePage',
        data: projectParam,
        requestType: 'body',
        showLoad: true,
        success: function(res) {
          if (res.errorCode === 200) {
            this.projectCodeList = res.data.records || [];
          }
        }.bind(this),
        error: function(res) {
          this.$message({
            type: 'error',
            message: res.body.msg || res.msg
          })
        }.bind(this)
      })
    },
    //项目编码change
    projectCodeChange(val){

      if(val) {
        for(let item of this.projectCodeList){
          if(item.projectCode === val){
            this.paramForm.projectId = item.id;
          }
        }
        this.paramForm.sampleLineParamList.forEach(item=>{
          item.projectLineCode = '';
          item.projectLineId = '';
          item.industrySegmentation = '';
          item.longsysPN = '';
          item.platform = '';
          item.chipModel = '';
          item.lockFw = '';
        })
      } else {
        this.paramForm.projectId = '';
      }
    },
    //子行编码 弹窗
    showDigLineCode(index){
      this.$refs.digLineCodeRef.visible = true;
      this.$refs.digLineCodeRef.lineCodeIndex = index;
    },
    // 设置子行信息
    setLineInfo(row, index){
      for(let item of this.paramForm.sampleLineParamList){
        if(row.lineCode === item.projectLineCode){
          this.$message('当前行已存在相同子行编码');
          return;
        }
      };
      this.paramForm.sampleLineParamList[index].projectLineCode = row.lineCode;
      this.paramForm.sampleLineParamList[index].projectLineId = row.lineId;
      this.paramForm.sampleLineParamList[index].industrySegmentation = row.industrySegmentation;
      this.paramForm.sampleLineParamList[index].longsysPN = row.projectPn;
      this.paramForm.sampleLineParamList[index].platform = row.platform;
      this.paramForm.sampleLineParamList[index].chipModel = row.chipModel;
      this.paramForm.sampleLineParamList[index].lockFw = row.lockFw;
      this.paramForm.sampleLineParamList[index].itemLevel = row.itemLevel;

    },
    //新增行
    addRow(){
      this.paramForm.sampleLineParamList.push(JSON.parse(JSON.stringify(this.sampleLineParamObj)));
    },
    deleteRow(index){
      this.$confirm('确定删除?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
          let id = this.paramForm.sampleLineParamList[index].id;
          if(!id){
            this.paramForm.sampleLineParamList.splice(index, 1);
            this.$message.success('删除成功');
            return;
          }
          this.$ajax.post({
            domain: 'crmUrl',
            url: 'sampleImport.deleteSampleLine',
            data: {id: id},
            requestType: 'body',
            showLoad: true,
            success: function (res) {
              if (res.errorCode === 200) {
                this.paramForm.sampleLineParamList.splice(index, 1);
                this.$message.success('删除成功');
              }
            }.bind(this),
            error: function (res) {
              this.$message({
                type: 'error',
                message: res.body.msg || res.msg
              })
            }.bind(this)
          })

      }).catch(() => { });
    },
    //By类型标识及ID查询行表或者子表信息
    getBySampleFlagAndId(flag, id,sampleId){

      this.$ajax.post({
        domain: 'crmUrl',
        url: 'sampleImport.getBySampleFlagAndId',
        data: {flag, id,sampleId},
        requestType: 'body',
        showLoad: true,
        success: function (res) {
          if (res.errorCode === 200) {
              let data = res.data;
              if(data.status=='submit'){
                data.status = 'audited'
              }
             this.sampleId=data.id;
               debugger;
              if(data.status == 'audited' && this.disabledForm) {
                this.btns[0].btnEvent = 'update';
                this.btns[0].title = '更新进度';
                this.btns[1].show = false;

                this.btns.push(
                  {
                    title: '封样',
                    btnEvent: 'sealed',
                    size: 'mini',
                    circle: false,
                    type: 'warning',
                    show: true,
                    icon: 'el-icon-takeaway-box'
                  },
                );

              }else{
              debugger
                if(!this.isChange && data.status != 'draft') {
                  this.btns[0].show = false;
                  this.btns[1].show = false;
                }
              }
              data.informerParamList.forEach(item=>{
                item.uid = item.userId;
                item.name = item.userName;
              })
             this.baseInfo.customer= data.customer;
             this.paramForm = Object.assign(this.paramForm, data);
             this.$refs.awsOrgSaleRef.reset([{name: data.salesName, uid: data.salesId}]);
             this.$refs.assistantRef.reset([{name: data.assistantName, uid: data.assistantId }]);
             this.$refs.orgInfoRef.reset(data.informerParamList);

             let filesList = [];
             data.attachFileInfoList.forEach(item =>{
               filesList.push({
                   size: item.fileSize,
                   name: item.fileName,
                   response: {
                     data: {
                       fileId: item.fileId,
                     }
                   }
               })
             })
             this.$refs.lsUploadRef.reset(filesList);

             if(flag == 'line'){
                data.sampleLineParams.forEach(item=>{
                   item.trialQuantity = this.$common.getComdifyNumber(item.trialQuantity);
                   item.outputQuantity = this.$common.getComdifyNumber(item.outputQuantity);
                   item.samplePurpose = item.samplePurpose.split(',');
                   this.productRow.push(item);
                })
                this.paramForm.sampleLineParamList = data.sampleLineParams;
              } else {
                data.sampleImportParam.trialQuantity = this.$common.getComdifyNumber(data.sampleImportParam.trialQuantity);
                data.sampleImportParam.outputQuantity = this.$common.getComdifyNumber(data.sampleImportParam.outputQuantity);
                data.sampleImportParam.samplePurpose = data.sampleImportParam.samplePurpose.split(',');
                this.paramForm.sampleLineParamList.push(data.sampleImportParam);
                this.productRow.push(data.sampleImportParam);
              }
          }
        }.bind(this),
        error: function (res) {
          this.$message({
            type: 'error',
            message: res.body.msg || res.msg
          })
        }.bind(this)
      })
    },
    //申请数量失去焦点
    applyQuantityBlur(val, i){
      if(Number(val) > 1000){
        this.paramForm.sampleLineParamList[i].applyQuantity = '',
        this.$message('申请样品，数量上限1000pcs');
      }
    },
    //获取下拉框数据
    async getSelectList(val){
      this.freeList = await commonSelect.initDictDataPost(this, 'Crm_Fee');
      this.freeSettlementList = await commonSelect.initDictDataPost(this, 'Crm_Free_Settlement');
      this.chipModelList = await commonSelect.initDictDataPost(this, 'Crm_Main_Chip_Model');
    },
    //是否收费
    async isChargeChange(val){
      if(val){
       this.freeSettlementList = await commonSelect.initDataValuePost(this, 'Crm_Free_Settlement', val);
       if(this.freeSettlementList.length === 1){
         this.paramForm.settleCharge = this.freeSettlementList[0].ext1;
       } else {
         this.paramForm.settleCharge = '';
       }
      } else {
        this.paramForm.settleCharge = '';
        this.freeSettlementList = await commonSelect.initDictDataPost(this, 'Crm_Free_Settlement');
      }
    },
    async freeSetChange(ext1){
      if(ext1){
        this.freeSettlementList.forEach(item=>{
          if(item.ext1 == ext1){
            this.paramForm.chargeSample = item.vaule;
          }
        })
      } else {
        this.freeSettlementList = await commonSelect.initDictDataPost(this, 'Crm_Free_Settlement');
      }
    },
    //承认样品时间 change
    recTimeChange(val, index){
      if(val){
         let recDate = Date.parse(val);
         let actualDate =  Date.parse(this.paramForm.sampleLineParamList[index].actualDate);
         let trialDate = Date.parse(this.paramForm.sampleLineParamList[index].trialDate);
         if( !isNaN(actualDate) && actualDate > recDate ){
           this.$message.warning('承认样品时间必须大于等于实际送样时间');
           this.paramForm.sampleLineParamList[0].recDate = '';
           return;
         }
         if( !isNaN(trialDate) && recDate > trialDate ){
           this.$message.warning('小批试产时间必须大于等于承认样品时间');
           this.paramForm.sampleLineParamList[0].recDate = '';
         }
      }

    },
    //实际送样时间 change
    actualTimeChange(val, index){
      if(val){
         let actualDate  = Date.parse(val);
         let recDate = Date.parse(this.paramForm.sampleLineParamList[index].recDate);
         if( !isNaN(recDate) && actualDate > recDate ){
           this.$message.warning('实际送样必须小于等于承认样品时间');
           this.paramForm.sampleLineParamList[0].actualDate = '';
         }
      }
    },
    //小批试产 时间 change
    trialTimeChange(val, index){
      if(val){
         let trialDate  = Date.parse(val);
         let actualDate =  Date.parse(this.paramForm.sampleLineParamList[index].actualDate);
         let outputDate = Date.parse(this.paramForm.sampleLineParamList[index].outputDate);
         if( !isNaN(actualDate) &&  actualDate  > trialDate){
           this.$message.warning('小批试产时间必须大于等于承认样品时间');
           this.paramForm.sampleLineParamList[0].trialDate = '';
           return;
         }
         if( !isNaN(outputDate) &&  outputDate  < trialDate){
           this.$message.warning('小批试产时间必须小于等于实际量产时间');
           this.paramForm.sampleLineParamList[0].trialDate = '';
         }
      }
    },
    //实际量产时间
    outputTimeChange(val, index){
      if(val){
         let outputDate  = Date.parse(val);
         let trialDate = Date.parse(this.paramForm.sampleLineParamList[index].trialDate);
         if( !isNaN(trialDate) && trialDate > outputDate ){
           this.$message.warning('实际量产时间必须大于等于小批试产时间');
           this.paramForm.sampleLineParamList[0].outputDate = '';
         }
      }
    },

    // 保存/提交
    saveForm(status) {
      if(!this.paramForm.sampleLineParamList.length){
        this.$message('请添加行数据!');
        return;
      }

      this.$refs['formRef'].validate((valid) => {

          if(!valid) { return; }
          let param = JSON.parse(JSON.stringify(this.paramForm));
          //param.status = status;
          param.salesId = param.salesNameAry[0].uid;
          param.salesName = param.salesNameAry[0].name;
          param.assistantId = param.assistantNameAry[0].uid;
          param.assistantName = param.assistantNameAry[0].name;
          param.sampleLineParamList.forEach(item=>{
            item.applyQuantity = item.applyQuantity?Number(item.applyQuantity):null;
            item.samplePurpose = item.samplePurpose.join(',');
          })
          param.attachFileInfoList = [];
          param.filesList.forEach(item=>{
            param.attachFileInfoList.push(
                {
                    busId: this.baseInfo.id,
                    modelId: '3101',
                    modelName: '项目模块',
                    fileId: item.response.data.fileId,
                    fileName: item.name,
                    fileSize: item.size,
                }
            );
          })
          param.informerParamList.forEach(item=>{
             item.userId = item.uid;
             item.userName = item.name;
          })

          delete param.assistantNameAry;
          delete param.filesList;
          delete param.salesNameAry;
        debugger;
          this.$ajax.post({
              domain: 'crmUrl',
              url: 'sample.saveSample',
              data: param,
              requestType: 'body',
              showLoad: true,
              success: function (res) {
                  if (res.errorCode === 200) {
                    if (status=='submit') {
                      this.paramForm.id=res.data.id;
                      this.doSubmit();
                    }else if(status=='processId'){

                    }else {
                      this.$message({
                        type: 'success',
                        message:'保存成功'
                      });
                      this.backCallBack();
                    }
                  }
              }.bind(this),
              error: function (res) {
                this.$message({
                  type: 'error',
                  message: res.body.msg || res.msg
                })
              }.bind(this)
          })

       });
    },

    //提交样品申请
    doSubmit(){
      console.log("busId:" + this.paramForm.id);
      let param = {
        busId: this.paramForm.id,
        moduleId: 3109,
        startType:  'Project_Sample',
      }
      this.$ajax.post({
        domain: 'crmUrl',
        url: 'sample.doSubmit',
        data: param,
        requestType: 'body',
        showLoad: true,
        success: function (res) {
          if (res.errorCode === 200) {
            this.backCallBack();
            this.$message.success("申请流程提交成功");
          }
        }.bind(this),
        error: function (res) {
          this.$message.error( res.body.msg || res.msg);
        }.bind(this)
      })
    },

    //更新 样品进度
   handleUpdate(){
      this.$refs['formRef'].validate((valid) => {
        debugger;
          if(!valid) { return; }

          let param = {};
          param = JSON.parse(JSON.stringify(this.paramForm));
          if(this.flag === 'line') {
            for(let item of param.sampleLineParams){
              if(!item.sampleStatus){
                this.$message.warning('请选择样品状态');
                return;
              }
              item.samplePurpose = item.samplePurpose.join(',');
              item.trialQuantity = this.$common.delcommafy(item.trialQuantity);
              item.outputQuantity = this.$common.delcommafy(item.outputQuantity);
            }
          } else {
            if(!param.sampleImportParam.sampleStatus){
              this.$message.warning('请选择样品状态');
              return;
            }
            param.sampleImportParam.samplePurpose = param.sampleImportParam.samplePurpose.join(',');
            param.sampleImportParam.trialQuantity = this.$common.delcommafy(param.sampleImportParam.trialQuantity);
            param.sampleImportParam.outputQuantity = this.$common.delcommafy(param.sampleImportParam.outputQuantity);
          }

          delete param.assistantNameAry;
          delete param.filesList;
          delete param.salesNameAry;
          delete param.sampleLineParamList;
          debugger
          this.$ajax.post({
              domain: 'crmUrl',
              url: 'sampleImport.updateBySampleFlagAndId',
              data: JSON.stringify(param),
              requestType: 'body',
              showLoad: true,
              success: function (res) {
                  if (res.errorCode === 200) {
                    this.$message({
                      type: 'success',
                      message: '保存成功'
                    });
                    setTimeout(()=>{
                      this.backCallBack();
                    }, 500)
                  }
              }.bind(this),
              error: function (res) {
                this.$message({
                  type: 'error',
                  message: res.body.msg || res.msg
                })
              }.bind(this)
          })

       });
   },

   //封样
   sealedSample(){

      this.$refs['formRef'].validate((valid) => {
        if(!valid) { return; }

        this.$confirm('确定封样?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {

          let param = [];
          let item = JSON.parse(JSON.stringify(this.paramForm.sampleLineParamList[0]));
          item.applyQuantity = item.applyQuantity?Number(item.applyQuantity):null;
          item.trialQuantity = this.$common.delcommafy(item.trialQuantity);
          item.outputQuantity = this.$common.delcommafy(item.outputQuantity);

          item.sealSample = 'Y';
          delete item.samplePurpose;
          param.push(item);

          this.$ajax.post({
              domain: 'crmUrl',
              url: 'sampleImport.updateSealSample',
              data: param,
              requestType: 'body',
              showLoad: true,
              success: function (res) {
                  if (res.errorCode === 200) {
                    this.$message({
                      type: 'success',
                      message: '封样成功'
                    });
                    setTimeout(()=>{
                      this.backCallBack();
                    }, 500)
                  }
              }.bind(this),
              error: function (res) {
                this.$message({
                  type: 'error',
                  message: res.body.msg || res.msg
                })
              }.bind(this)
          })

        }).catch(() => { });

      });

   },

    // 导航栏按钮操作
    clickbtn(type) {
      switch (type) {
        case 'save':
          this.saveForm('draft');
          break;
        case 'submit':
          this.saveForm('submit');
          break;
        case 'update':
          this.handleUpdate();
          break;
        case 'sealed':
          this.sealedSample();
          break;
      }
    },
    //自定义返回函数
    backCallBack() {
      if(this.backRouteUrl){
        this.$router.push(this.backRouteUrl);
      }else if(this.paramForm.projectId && this.flag){
        this.$router.push({
            name: 'projectDetail',
            params: {projectId: this.paramForm.projectId, activeTab: 'sampleProgress'} ,
        });
      }else if(this.paramForm.projectId){
        this.$router.push({
            name: 'projectDetail',
            params: {projectId: this.paramForm.projectId} ,
        });
      }  else {
        this.$router.go(-1);
      }

    },

  },
  computed:{
    sid(){
      return this.$common.getUrlParams('sid');
    }
  },
  data(){
    return {
      isProccess:false,
      isChange:false,
      btns: [
        {
          title: '保存',
          btnEvent: 'save',
          size: 'mini',
          circle: false,
          type: 'primary',
          isplain: true,
          show: true,
          icon: 'el-icon-check'
        },
        {
          title: '提交',
          btnEvent: 'submit',
          size: 'mini',
          circle: false,
          type: 'primary',
          show: true,
          icon: 'el-icon-upload2'
        }
      ],
      isApploval:'',
      processId:'',
      taskRefId:'',
      baseInfo: {},//项目头信息
      productRow: [], //产品行
      flag: '', //标识是 子行(line)更新，还是 子行的子表(item)项更新
      sampleId: '',
      rowId: '', //存 操作行的 id
      backRouteUrl: '',
      disabledForm: false, //表单不可操作

      paramForm: {
        projectId: '',
        sampleCode: '', //样品编码
        customer: '',
        customerId: '',
        customerType: '',
        agentName: '',
        agentId: '',
        projectCode: '',

        salesName: '',
        salesId: '',
        assistantName: '', //商务人员
        assistantId: '',
        expectDate: '', //期望送货日期
        status: 'draft', //状态 draft: 草稿，submit: 提交

        chargeSample: '',  //是否收费
        settleCharge: '', //费用结算
        salesNameAry: [], //销售人员数组
        assistantNameAry: [], //商务人员
        informerParamList: [], //知会人
        remarks: '', //备注

        personContact: '', //联系人
        phone: '',
        sampleAddr: '', //送样地址

        sampleLineParamList: [],  //关联样品行列表

        attachFileInfoList: [], //附件
        filesList: [], //文件数组

      },
      sampleLineParamObj: {//关联样品行 对象
        projectLineCode: '', //子行编码(产品行CODE)
        projectLineId: '', //产品行id
        industrySegmentation: '',// 细分领域
        longsysPN: '',
        platform: '',
        chipModel: '',
        lockFw: '',
        needForecast: '',
        needSample: '', //样品需求
        samplePurpose: ['shipment'],
        custRequired: '',
        applyQuantity: '',
        itemLevel:''
      },

      agentCustomerList: [], //代理商数据列表
      projectCodeList: [], //项目编码列表

      rules: {
        projectCode: [ {required: true, message: '不能为空', trigger: 'blur'} ],
        agentName: [ {required: true, message: '请选择', trigger: 'change'}],
        customer: [ {required: true, message: '请选择', trigger: 'change'}],
        projectCode: [ {required: true, message: '请选择', trigger: 'change'}],
        salesNameAry: [ {required: true, message: '请选择', trigger: 'change'}],
        assistantNameAry: [ {required: true, message: '请选择', trigger: 'change'}],
        expectDate: [ {required: true, message: '请选择', trigger: 'change'}],

        chargeSample: [ {required: true, message: '请选择', trigger: 'change'}],
        settleCharge: [ {required: true, message: '请选择', trigger: 'change'}],
        personContact: [{required: true, message: '请输入', trigger: 'blur'}],
        phone: [
          {required: true, message: '请输入', trigger: 'blur'},
          { pattern: /^[0-9]{5,15}$/, message: '请输入有效电话', trigger: 'change' },
        ],
        sampleAddr: [{required: true, message: '请输入', trigger: 'blur'}],

      },
      freeSettlementList: [],
      chipModelList: [], // 芯片型号
      freeList: [],
      lockFwList: [
        { label: '是', value: 'Y'},
        { label: '否', value: 'N'}
      ],


      testReportList: [
        { label: '需要', value: '需要'},
        { label: '不需要', value: '不需要'}
      ],
      admitList: [
        { label: '需要', value: '需要'},
        { label: '不需要', value: '不需要'}
      ],
      sampleResultList: [
        {
          value: '通过',
          label: '通过'
        },
        {
          value: '未通过',
          label: '未通过'
        },
      ],

      pickerOptions: {
        disabledDate(time) {
          return time.getTime() < Date.now();
        }
      },

    }
  }
}
</script>

<style lang="scss"  >
 @import '@/pages/project/list/scss/form.scss';
</style>
<style lang="scss"  scoped>
 .ls-container.ls-project{
   padding: 20px 15px;
   overflow-y: auto;
   .tampalte-contain {
     .info-box.el-row {
       margin-top: 10px;
     }
   }
   .file-input {
     display: none;
   }
   .position-p{
     position: absolute;
     top: 0;
     right: 6px;
     color: #606266;
   }
   /deep/ .red.el-textarea{
     .el-textarea__inner {
       color: red!important;
     }
   }
 }
</style>
