// 贸理通V3.1 - 开始

// 审批结论发生改变
$('[name=approvalConclusion]').change(function () {
  if ($('[name=approvalConclusion]:checked').val() == 'pass') {
    $('.validBox').show()
    $('.approvalConclusionTd').attr('colspan', 0)
    $('.approvalConclusionTd').attr('width', '35%')
    $('[name=purchContractApprovalUpload]').change()
    $('[name=signMode]').change()
  } else {
    $('.validBox').hide()
    $('.signModeChange').hide()
    $('.contractTable').hide()
    $('.approvalConclusionTd').attr('colspan', 3)
    $('.approvalConclusionTd').attr('width', '85%')
    $('.createProcurementContract').hide()
  }
})

// 合同签署方式发生改变
$('[name=signMode]').change(function () {
  if ($('[name=signMode]:checked').val() == '1') {
    $('.signModeChange').show()
    // $('.createProcurementContract').show()
    $('[name=purchContractApprovalUpload]').change()
    $('.createProcurementContract').click()
  } else {
    $('.signModeChange').hide()
    $('.contractTable').hide()
    $('.createProcurementContract').hide()
  }

})

// 上传合同文件发生改变
$('[name=purchContractApprovalUpload]').change(function () {
  if ($('[name=purchContractApprovalUpload]:checked').val() == '1') {
    $('.contractTable').show()
  } else {
    $('.contractTable').hide()
  }
})



// 排序
function sortReceiptInfo() {
  $(".contractListTbody").each(function (i, ele) {
    if ($('.contractListTable').find('tr').eq(0).css('display') === 'table-row') {
      $(ele).find('td:first span').text(i + 1);
    } else {
      $(ele).find('td:first span').text(i);
    }
  });
  if ($('.contractListTable').find('tr').eq(0).css('display') === 'table-row') {
    if ($(".contractListTbody").length <= 1) {
      $('.contractTable .negativeInformationReduce').hide();
    } else {
      $('.contractTable .negativeInformationReduce').show();
    };
  } else {
    if ($(".contractListTbody").not(':first').length <= 1) {
      $('.contractTable .negativeInformationReduce').hide();
    } else {
      $('.contractTable .negativeInformationReduce').show();
    };
  }
};

// 添加行
$(".contractTable").on('click', '.negativeInformationPlus', function () {
  var supplierTrClone = $(".contractListTbody:first").clone();
  supplierTrClone.find('.negativeInformationReduce').show();
  supplierTrClone.find('.contractName').val('')
  supplierTrClone.find('.error').hide();
  supplierTrClone.find('[name=contractType]').val('true')
  setTimeout(() => {
    supplierTrClone.find('.btn-delete-file').click()
    supplierTrClone.find('.btn-delete-originalfile').click()
    supplierTrClone.data('deletefileid', [])
  }, 100);
  supplierTrClone.show()
  $(this).parents('.contractListTbody').after(supplierTrClone);
  sortReceiptInfo()
  initDepositListData('.fileListBox', supplierTrClone)
});


// 删除行
$(".contractTable").on('click', '.negativeInformationReduce', function () {
  $(this).parents('.contractListTbody').remove();
  sortReceiptInfo();
});

// 生成采购合同文件
$('.createProcurementContract').click(function (e) {
  $.ajax({
    url: `/purchContract/change/makeContractPdf?otherConvention=${$('[name=otherConvention]').val()}&businessKey=${$('[name=businessKey]').val()}`,
    type: 'get',
    processData: false,
    contentType: false,
    success: function (data) {
      if (data.success) {
        new $.zui.Messager('生成采购合同文件成功', {
          type: 'success'
        }).show();
        $('[name=signMode]').get(0).checked = true
        $('.signModeChange').show()
        $('[name=purchContractApprovalUpload]').change()
        $('[name=useContract]').prop('checked', true)
        const fileStorage = data.data
        $('.procurementContract').find('.fileListBox .fileContent').empty()
        const procurementContractStr = `
          <div class="fileStorage" style="display:none">
            <input type="text" class="originalId"   value="${fileStorage.id}">
            <input type="text" class="originalUrl"  value="${fileStorage.path}">
            <input type="text" class="originalType" value="${fileStorage.fileType}">
            <input type="text" class="originalName" value="${fileStorage.originalName}">
            <input type="text" class="originalSize" value="${fileStorage.size}">
          </div>
        `
        showOriginalFile(procurementContractStr, $('.procurementContract').find('.fileListBox'), 'onlyView')
      } else {
        new $.zui.Messager('生成采购失败:' + data.msg, {
          type: 'danger'
        }).show();
      }
    },
    error: function (status) {
      new $.zui.Messager('生成采购时发生错误:' + status, {
        type: 'danger'
      }).show();
    }
  });
})

// 贸理通V3.1 - 结束
function initSignType() {
  // if(submitStatus === 'create') {
      $('[name=signMode]').get(1).checked = true
      $('[name=signMode]').change()
  // }

}

$(function () {
  // 贸理通V3.1 - 开始
  if (!$('[name=approvalConclusion]:checked').val()) {
    $('[name=approvalConclusion]').get(0).checked = true
  }
  if(!$('[name=purchContractApprovalUpload]:checked').val()) {
    $('[name=purchContractApprovalUpload]').get(1).checked = true
  }
  $('[name=approvalConclusion]').change()
  // if ($('.procurementContractFileStorage')) {
  //   showOriginalFile($('.procurementContractFileStorage'), $('.procurementContract').find('.fileListBox'))
  // }
  sortReceiptInfo()
  uploadFileMethod({
    mainDom: '#contractSignCheck-form',
    delegateDom: '.choiceFile',
    insideDelegateDom: '.fileContent',
    delegateDomInput: '.contractTable .contractListTbody .fileinput',
    depositDataDom: '.fileListBox',
    delegateLabel: '.fileListBox',
    displayListDom: '.uploaderFile',
    isCustomUploadBtn: false,
  })
  // 贸理通V3.1 - 结束


  //提交
  function submitFunction(e) {
    // $(".newTabAddUpdateBtnBox .save,.newTabAddUpdateBtnBox .btn-cancel").addClass("loadingCircle");
    var postdata = new FormData(), tipword = "提交";
    postdata.append('taskId', $('[name=taskId]').val() === 'null' ? '' : $('[name=taskId]').val())
    postdata.append('businessKey', $('[name=businessKey]').val())
    postdata.append('approvalConclusion', $('[name=approvalConclusion]:checked').val())
    postdata.append('approvalComment', $('[name=approvalComment]').val())
    postdata.append('otherConvention', $('[name=otherConvention]').val())
    if ($('[name=approvalConclusion]:checked').val() == 'pass') {
      postdata.append('signMode', $('[name=signMode]:checked').val())
      if ($('[name=signMode]:checked').val() == '1') {
        postdata.append('upload', $('[name=purchContractApprovalUpload]:checked').val())
        postdata.append('useContract', $('[name=useContract]').prop('checked') ? 1 : 0)
        // postdata.append('signFile', $('.procurementContractFileStorage').find('.originalId').val())

      }
      if ($('[name=purchContractApprovalUpload]:checked').val() == '1') {
        let contractListTbodyData = $('.contractListTable').find('tr').eq(0).css('display') === 'table-row' ? $('.contractListTbody') : $('.contractListTbody').not(':first')
        for (let j = 0; j < contractListTbodyData.length; j++) {
          let el = contractListTbodyData[j]
          if (!$(el).find('.contractName').val()) {
            new $.zui.Messager('请输入合同名称', {
              type: 'success'
            }).show();
            return
          }
          let file = $(el).find('td').eq(3).find('.fileListBox').data('filearray')
          if (!file.length) {
            new $.zui.Messager('请上传附件', {
              type: 'success'
            }).show();
            return
          }
          postdata.append('uploadPurchSupplementContracts[' + j + '].contractName', $(el).find('.contractName').val())
          postdata.append('uploadPurchSupplementContracts[' + j + '].file', file[0])
        }
      }
    }
    $.ajax({
      url: '/purchContract/change/approval/doAudit',
      type: 'post',
      data: postdata,
      processData: false,
      contentType: false,
      success: function (data) {
        if (data.success) {
          new $.zui.Messager(tipword + '成功', {
            type: 'success'
          }).show();

          $(".yk_rightcontent").load('/purchContract/list');

        } else {
          new $.zui.Messager(tipword + '失败:' + data.msg, {
            type: 'danger'
          }).show();
          // $(".newTabAddUpdateBtnBox .save,.newTabAddUpdateBtnBox .btn-cancel").removeClass("loadingCircle");
        }
      },
      error: function (status) {
        new $.zui.Messager(tipword + '时发生错误:' + status, {
          type: 'danger'
        }).show();
        // $(".newTabAddUpdateBtnBox .save,.newTabAddUpdateBtnBox .btn-cancel").removeClass("loadingCircle");
      }
    });
    return false;
  };

  var formRules = {
    approvalConclusion: {
      required: true
    },
    signMode: {
      required: true
    },
    purchContractApprovalUpload: {
      required: true
    }
  };
  var formMessages = {
    approvalConclusion: {
      required: '请选择审批结论'
    },
    signMode: {
      required: '请选择签署方式'
    },
    purchContractApprovalUpload: {
      required: '请选择上传合同文件'
    }
  };

  //表单验证
  function addNewCustomer(e) {
    $("#contractSignCheck-form").validate({
      promptPosition: "bottomLeft",
      submitHandler: function (form) {
        submitFunction(e);
      },
      rules: formRules,
      messages: formMessages
    });
  };

  // 提交按钮
  //$(".yk_addNewMsg .save").click(addNewCustomer);
  $(".yk_addNewMsg .save").click(function (e) {
    if (!$(this).hasClass('loadingCircle')) {
      addNewCustomer(e);
    };
  });

  // 关闭按钮
  $(".yk_addNewMsg .btn-cancel,.newBackBtn").click(function () {
    if (!$(this).hasClass('loadingCircle')) {
      $(".yk_rightcontent").load('/purchContract/list');
    };
    return false;
  });
})
