<template>
  <div class="app-container">

    <div class = "search-bx"  >
        <div class="search">
          <el-row :gutter="0">

              <el-input v-model="tableObj.getdataListParm.parammaps.contractCode" placeholder="合同编号" class="filter-item" style="width: 120px" />

              <!-- <el-autocomplete v-model="tableObj.getdataListParm.parammaps.customerName" :fetch-suggestions="customer_search" placeholder="客户名称" style="width: 200px;margin-right:10px" @select="change_customer_select" @clear="clear_customer_select" @blur="customer_search_blur" clearable>
                <template slot-scope="{ item }">
                  <span class="name">{{ item.name }}</span>
                </template>
              </el-autocomplete> -->

              <el-input v-model="tableObj.getdataListParm.parammaps.customerName" placeholder="客户名称" style="width: 180px;" class="filter-item" clearable />

              <el-select v-model="tableObj.getdataListParm.parammaps.groupId" placeholder="集团" class="filter-item" style="width: 120px;" clearable>
                <el-option v-for="item in groupNameList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>

              <el-date-picker v-model="tableObj.getdataListParm.parammaps.inputDatetime1" class="inputDatetime filter-item" type="daterange" range-separator="至" start-placeholder="合同开始日期" end-placeholder="合同开始日期" style="width: 250px;" />

              <el-date-picker v-model="tableObj.getdataListParm.parammaps.inputDatetime2" class="inputDatetime filter-item" type="daterange" range-separator="至" start-placeholder="合同结束日期" end-placeholder="合同结束日期" style="width: 250px;" />


              <el-select v-model="tableObj.getdataListParm.parammaps.contractStatus" placeholder="合同状态" class="filter-item" style="width: 120px;" clearable>
                  <el-option v-for="item in statusNameList" :key="item.id" :label="item.name" :value="item.id" />
              </el-select>


              <el-input v-model="tableObj.getdataListParm.parammaps.beginContractMoney" placeholder="合同金额" style="width:80px"></el-input>
                -
              <el-input v-model="tableObj.getdataListParm.parammaps.endContractMoney" placeholder="合同金额" style="width:80px"></el-input>


              <el-input v-model="tableObj.getdataListParm.parammaps.beginMoneyStep" placeholder="款项分期" style="width:80px"></el-input>
                -
              <el-input v-model="tableObj.getdataListParm.parammaps.endMoneyStep" placeholder="款项分期" style="width:80px"></el-input>


             <el-date-picker v-model="tableObj.getdataListParm.parammaps.inputDatetime3" class="inputDatetime filter-item" type="daterange" range-separator="至" start-placeholder="创建时间" end-placeholder="创建时间" style="width: 250px;" />


              <el-select v-model="tableObj.getdataListParm.parammaps.createrId" placeholder="创建人" class="filter-item" style="width: 120px;" clearable filterable>
              <el-option v-for="(item,index) in createrNameList" :key="index" :label="item.name" :value="item.id" />
            </el-select>


                <el-button class="successBorder" @click="form_search">查询</el-button>
                <el-button class="successBorder" @click="form_clear">重置</el-button>

          </el-row>
        </div>


    </div>


    <div class="table"    >
      <el-table :key="tableObj.tableKey" v-loading="tableObj.listLoading" element-loading-text="给我一点时间" :data="tableObj.list" border fit highlight-current-row style="width: 100%;" :row-style="rowStyle" :cell-style="cellStyle" class="elTable table-fixed" :max-height="myHeight">


        <el-table-column label="序号" align="center" type="index" width="50px"  fixed="left">
          <template slot-scope="scope">
            <span>{{ scope.$index + (tableObj.pageNum-1) * tableObj.pageSize + 1 }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合同编号" min-width="130px" align="center"  fixed="left">
          <template slot-scope="scope">
            <span  style = "color:#409EFF; cursor: pointer;" @click="form_see(scope.row)">{{ scope.row.contractCode  }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合同状态" min-width="90px" align="center"  fixed="left">
          <template slot-scope="scope">
            <span>{{ scope.row.contractStatus }}</span>
          </template>
        </el-table-column>
        <el-table-column label="客户名称" min-width="120px" align="center" show-overflow-tooltip >
          <template slot-scope="scope">
            <span>{{ scope.row.customerName }}</span>
          </template>
        </el-table-column>
         <!-- <el-table-column label="营业执照" min-width="110px" align="center" show-overflow-tooltip>

            <template slot-scope="scope">
              <img  style="width: 50px; height: 50px" :src="scope.row.imgUrlDetil" alt="">
            </template>

        </el-table-column> -->
        <el-table-column label="所属集团" min-width="90px" align="center"  >
          <template slot-scope="scope">
            <span>{{ scope.row.groupName }}</span>
          </template>
        </el-table-column>

        <el-table-column label="合同金额(元)" min-width="110px" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.contractMoney }}</span>
          </template>
        </el-table-column>
        <el-table-column label="款项分期" min-width="120px" align="center">
          <template slot-scope="scope">
            <span>{{ scope.row.moneyStep }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合同开始时间" min-width="110px" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.contractBeginDate  }}</span>
          </template>
        </el-table-column>
        <el-table-column label="合同结束时间" min-width="110px" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.contractEndDate  }}</span>
          </template>
        </el-table-column>
        <el-table-column label="创建时间" min-width="110px" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.createrDate  }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="120px" align="center" show-overflow-tooltip>
          <template slot-scope="scope">
            <span>{{ scope.row.remark  }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center"  :width="autoWidth"  v-if="autoWidth !== 0"    class-name="small-padding fixed-width" fixed="right">
          <template slot-scope="{row}">


            <el-button class="miniSuccess" @click="form_adopt(row)" v-if="roleSet(row)">通过</el-button>

             <el-button class="miniDanger" @click="form_reject(row)" v-if="roleSet(row)">驳回</el-button>
             <el-button class="miniSuccess" v-if="row.contractStatus == '一审中' || row.contractStatus == '二审中' || row.contractStatus == '三审中' || row.contractStatus == '四审中' || row.contractStatus == '五审中'" @click="form_quick(row)"  >催进度</el-button>


          </template>
        </el-table-column>

      </el-table>

      <!-- <el-row :gutter="0">
        <el-col :span="6" :offset="12" style="color:#f00">
          列表合同总金额：{{tableSumMoney}}
        </el-col>
      </el-row> -->

      <pagination v-show="tableObj.total>=0" :total="tableObj.total" :page.sync="tableObj.getdataListParm.offset" :limit.sync="tableObj.getdataListParm.pagecount" @pagination="get_table_data" />
    </div>


    <!-- 查看/反馈 -->
    <el-dialog  title="合同详情" :visible.sync="createSee.dialogFormVisible" :close-on-click-modal="false" width="95%" :before-close="dialog_close_see">
      <div class="app-add">


              <ContractMoreDetail :conmore-data="conmoreData"  />


        <div slot="footer" class="dialog-footer">

          <el-button  class="success" v-if="roleSet(create.temp)"  @click="form_adopt(create.temp)">审核通过</el-button>
          <el-button  class="success" v-if="roleSet(create.temp)"  @click="form_reject(create.temp)">驳回</el-button>

          <!-- v-if="create.temp.contractStatus == '一审中' || create.temp.contractStatus == '二审中' || create.temp.contractStatus == '三审中' || create.temp.contractStatus == '四审中' || create.temp.contractStatus == '五审中'" -->
          <el-button class="success" v-if="create.temp.contractStatus == '一审中' || create.temp.contractStatus == '二审中' || create.temp.contractStatus == '三审中' || create.temp.contractStatus == '四审中' || create.temp.contractStatus == '五审中'"   @click="form_quick(create.temp)"  >催进度</el-button>
          <el-button class="cancelClose" @click="dialog_close_see()">关闭</el-button>


        </div>
      </div>
    </el-dialog>


    <!-- 通过 -->
    <el-dialog title="确认是否审核通过" :visible.sync="adopt.dialogFormVisible" :close-on-click-modal="false" width="40%"  :before-close="dialog_close_adopt">
      <div class="app-add">
        <el-form ref="adopttemp" :rules="adopt.rules" :model="adopt.temp" label-position="right" label-width="150px" style="width: 80%;margin:0 auto 50px">

          <el-form-item label="备注：" prop="remark">
            <el-input ref="remark" v-model="adopt.temp.remark" type="textarea" :autosize="{ minRows: 4, maxRows: 8} "  :rows="8" placeholder="请输入备注，最多200个字" maxlength="200" class="filter-item" style="width: 100%;"   />
          </el-form-item>


        </el-form>
        <div slot="footer" class="dialog-footer">

          <el-button class="cancelClose" @click="dialog_close_adopt()">关闭</el-button>
          <el-button class="success" @click="form_adopt_save()">确认</el-button>
        </div>
      </div>
    </el-dialog>

   <!-- 驳回 -->
    <el-dialog title="是否驳回申请" :visible.sync="reject.dialogFormVisible" :close-on-click-modal="false" width="40%" :before-close="dialog_close_reject">
      <div class="app-add">
        <el-form ref="rejecttemp" :rules="reject.rules" :model="reject.temp" label-position="right" label-width="150px" style="width: 80%;margin:0 auto 50px">

          <el-form-item label="驳回原因：" prop="remark">
            <el-input ref="remark" v-model="reject.temp.remark" type="textarea" :autosize="{ minRows: 4, maxRows: 8} "  :rows="8" placeholder="请输入备注，最多200个字" maxlength="200" class="filter-item" style="width: 100%;"   />
          </el-form-item>


        </el-form>
        <div slot="footer" class="dialog-footer">

          <el-button class="cancelClose" @click="dialog_close_reject()">关闭</el-button>
          <el-button class="success" @click="form_reject_save()">确认</el-button>
        </div>
      </div>
    </el-dialog>


  </div>
</template>

<script>


import { GetDataByName, PostDataByName, failproccess, ExecDataByConfig, GetDataByNames, checkButtons, calculativeWidth, wxpush } from '@/api/common'
import Cookies from 'js-cookie'
import { parseTime } from '@/utils/index.js'
// import littleTable from './components/littleTable'
import { getToken } from '@/utils/auth'
import Pagination from '@/components/Pagination'
import { MessageBox } from 'element-ui'

import ContractMoreDetail from '@/componentView/ContractMoreDetail.vue'
import ContractCustomerDetail from '@/componentView/ContractCustomerDetail.vue'


export default {
  name: 'ContractApproval',
  components: { Pagination , ContractCustomerDetail, ContractMoreDetail},
  data() {
    return {
      myHeight:document.documentElement.clientHeight - 85 - 160,
      autoWidth: 220,
      autoWidth: 230,
      employeid: Cookies.get('employeid'),
      disabled: false,
      g_userId: Cookies.get('g_userId'),


      dialogImageUrl: '',
      dialogVisible: false,
      dialogImageUrl2: '',
      dialogVisible2: false,

      rowData:{},
      isHome:"",


      //图片请求地址
      uploadImageUrl: process.env.VUE_APP_BASE_API + 'authdata/uploaderimage',
      //图片请求头
      headers: {
        optname: 'insertcustompic',
        id: 1,
        token: getToken() // 从cookie里获取token，并赋值token
      },
      //图片路径
      fileList: [],
      fileList2: [],


      isRoleEdit: [], isContractAdopt: [],


      activeName:'first',

      //客户资料详情组件
      conmoreData:{ id:"" },

      send_select_list: [
        { name: 'getDictListSelect', offset: 0, pagecount: 0, parammaps: { "pid": "54" } },
        { name: 'getUsersSelect', offset: 0, pagecount: 0, parammaps: {} },
         { name: 'getProductsEnable', offset: 0, pagecount: 0, parammaps: {} },
      ],

      customerNameList: [], // 客户名称
      groupNameList: [], // 集团


       // 下拉框 - 创建人
      createrNameList: [],

      // 下拉框 - 合同状态
      statusNameList: [
        { "name": "草稿", "id": "草稿" },
        { "name": "一审中", "id": "一审中" },
        { "name": "二审中", "id": "二审中" },
        { "name": "三审中", "id": "三审中" },
        { "name": "审核通过", "id": "审核通过" },
        { "name": "已撤销", "id": "已撤销" },
        { "name": "被驳回", "id": "被驳回" },
      ],

      // 下拉框 -款项分期
      moneyStepList: [
        { "name": "1", "id": "1" },
        { "name": "2", "id": "2" },
        { "name": "3", "id": "3" },
        { "name": "4", "id": "4" },
        { "name": "5", "id": "5" },
        { "name": "6", "id": "6" },
        { "name": "7", "id": "7" },
        { "name": "8", "id": "8" },
        { "name": "9", "id": "9" },
        { "name": "10", "id": "10" },
      ],


      //表格 - 列表 - 查询
      tableObj: {
        getdataListParm: {
          name: 'getContractApproval',
          page: 1,
          offset: 1,
          pagecount: 10,
          returntype: 'Map',
          parammaps: {
            roleId: Cookies.get('g_roleId'),
            userId: Cookies.get('g_userId'),
            contractCode: "",
            customerName: "",
            customerId: "",
            groupId: "",
            contractStatus: "",
            createrId: "",
            beginContractMoney: "",
            endContractMoney: "",
            beginMoneyStep: "",
            endMoneyStep: "",


            inputDatetime1: "",
            inputDatetime2: "",
            inputDatetime3: "",

            beginContractBeginDate: "",
            endContractBeginDate: "",
            beginContractEndDate: "",
            endContractEndDate: "",
            beginCreaterDate: "",
            endCreaterDate: "",


          }
        },
        tableKey: 0,
        list: [],
        total: 0,
        listLoading: true,
        temp: {}
      },


      tableSumMoney:1000,


      // 新增/编辑
      create: {
        dialogFormVisible: false,
        dialogStatus: '',
        temp: {  contractStatus: '',    customerId: '', groupId: '', groupName: '', serviceCode: '', contractBeginDate: parseTime(new Date(), '{y}-{m}-{d}'), contractEndDate: parseTime(new Date(), '{y}-{m}-{d}'), createrId:  Cookies.get('employeid'), createrName:  Cookies.get('employename'),moneyStep: '1',contractMoney: '', businessLicense: -1,picname1: '',userIds:""},

        rules: {
          // customerName: [{ required: true, message: '必填', trigger: 'blur' }],
          // serviceCode: [{ required: true, message: '必填', trigger: 'blur' }],
          // serviceBeginDate: [{ required: true, message: '必填', trigger: 'blur' }],
          // employeeId: [{ required: true, message: '必填', trigger: 'blur' }],
          // serviceTypeName: [{ required: true, message: '必填', trigger: 'blur' }],
          // serviceResult: [{ required: true, message: '必填', trigger: 'blur' }],
          // describe: [{ required: true, message: '必填', trigger: 'blur' }],
          // receiverName: [{ required: true, message: '必填', trigger: 'blur' }],
          // receiverTel: [{ required: true, message: '必填', trigger: 'blur' }],

          // businessLicense: [{ required: true, message: '必填', trigger: 'blur' }],

        },
        // 客户名称
        getdataListParmCust: {
          name: 'getCustomerByGroupId',
          returntype: 'Map',
          parammaps: { groupId: "" }
        },
        customerNameList:[],

        // 款项信息 - 表格
        getdataListParmStages: {
          name: 'getContractCost',
          returntype: 'Map',
          parammaps: { id: "" }
        },
        // 货物信息 - 表格
        getdataListParmStock: {
          name: 'getContractGoodsByCid2',
          returntype: 'Map',
          parammaps: { id: "" }
        },
      },


      createSee:{
        dialogFormVisible: false,
      },

      //款项期数表格
      tableStagesList:[
        {'stages':'1','planCostRate':'','planCost':'','collectionDate': parseTime(new Date(), '{y}-{m}-{d}'),'customerId':'','createrId':''}
      ],
      //下拉框 - 备货
      receProductNameList:[],
      //备货表格
      tableStockList:[],
      stockSumPrice:0,


      textMap: {
        create: '新增',
        see: '查看',
        update: '编辑'
      },


      //备货ID集合
      stockupIdArr: [],
      //备货表格集合
      tableArrList: [],


      // 通过
      adopt: {
        dialogFormVisible: false,
        dialogStatus: '',
        temp: { remark: '',  id: '' ,contractStatus:""},
        rules: {
          remark: [{ required: true, message: '必填', trigger: 'blur' }],
        }
      },
      // 驳回
      reject: {
        dialogFormVisible: false,
        dialogStatus: '',
        temp: { remark: '',  id: '' ,contractStatus:""},
        rules: {
          remark: [{ required: true, message: '必填', trigger: 'blur' }],
        }
      },


      moneyShow:true,
      //获取反馈记录
      getFeedRecordParm:{
          name: 'getServiceFeedbackById',
          page: 1,
          offset: 1,
          pagecount: 10,
          returntype: 'Map',
          parammaps: { id: "" }
      },
      //保存反馈记录
      feedRecordTemp:{
          name: 'insertServiceFeedback',
          page: 1,
          offset: 1,
          pagecount: 1000,
          returntype: 'Map',
          parammaps: {
            serviceId:"",
            createrId:"",
            remark:"",

          }

      },
      //反馈记录
      feedRecordList:[
        // {id:1, num: 1, txt: '主板缺失零件，疫情关系，无法采购，延期1天',   director:'epans', date:"2022-12-01"},
        // {id:1, num: 1, txt: '主板缺失零件，疫情关系，无法采购，延期1天',   director:'epans', date:"2022-12-01"},
        // {id:1, num: 1, txt: '主板缺失零件，疫情关系，无法采购，延期1天',   director:'epans', date:"2022-12-01"},
      ],

      requestParam: {},
      isokDisable: false,
      selectList: [],
      rowStyle: { maxHeight: 50 + 'px', height: 45 + 'px' },
      cellStyle: { padding: 0 + 'px' }
    }
  },

  watch: {


    // tableStagesList: {
    //   deep: true,
    //   handler: function (item) {
    //      //计算价格比例
    //       var contractMoney = this.create.temp.contractMoney
    //       var tableStagesList = this.tableStagesList
    //       for (let i = 0; i < tableStagesList.length; i++) {
    //         tableStagesList[i].planCost = parseFloat(tableStagesList[i].planCostRate) * contractMoney  * 0.01
    //       }
    //       this.tableStagesList = tableStagesList


    //   }
    // },


    tableStockList: {
      deep: true,
      handler: function (item) {
          //计算总价格
          var sum = 0
          this.tableStockList.forEach(function(i){
              sum = parseInt(i.nums) * parseFloat(i.price) + sum
          })
          this.stockSumPrice = sum

      }
    },

  },

  created() {

    this.get_select_list()
    this.get_auto_buttons()

    var rowData = this.$route.params.rowData
    var isHome = this.$route.params.isHome
    var codeNum = this.$route.params.codeNum

    if(isHome == 'home'){
      this.rowData = rowData
      this.isHome = isHome
      this.tableObj.getdataListParm.parammaps.contractCode = codeNum
      this.get_table_data()

    } else {
      this.rowData = {}
      this.isHome = ""
      this.codeNum = ""

      this.get_table_data()
    }
  },


  methods: {

    roleSet(row){
      var result = true
      console.log(row.userIds)

      if(row.userIds){
        if(this.isContractAdopt && row.userIds.split(',').includes(this.g_userId)){
          result = true
        } else{
          result = false
        }
      } else {
        result = false
      }
      // if(this.isRoleEdit  == '1' && row.userIds.split(',').includes(this.g_userId)){
      //   result = true
      // } else{
      //   result = false
      // }
      return result

    },
    //图片展示
    handlePicPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    handlePicChange(file, fileList) {

    },
    //文件上传成功后的操作
    handlePicSuccess(response, file, fileList) {
      console.log('文件上传成功时的钩子response', response, )
      console.log('文件上传成功时的钩子file', file)
      console.log('fileList', fileList)

      // //3张图片时，关闭新增的按钮
      if (fileList.length == 1) {
        document.getElementById('uploadPic').lastChild.style.display = "none"
      } else {
        document.getElementById('uploadPic').lastChild.style.display = "inline-block"
      }


      if (this.create.temp.businessLicense === undefined || this.create.temp.businessLicense == -1) {
        console.log("111")
        this.create.temp.businessLicense = response.execresult.LastInsertId
      }
      console.log('this.picArr1', this.picArr1)

      console.log('this.create.temp', this.create.temp)


    },
    //图片文件删除
    handlePicRemove(file, fileList) {
      console.log(file, '文件列表移除文件时的钩子file---')
      console.log(fileList, '文件列表移除文件时的钩子fileList--')
      // this.$set(this.create.temp, "businessLicense", -1)
      // this.$set(this.create.temp, "scenePhoto2", -1)
      // this.$set(this.create.temp, "scenePhoto3", -1)
      //9张图片时，关闭新增的按钮
      if (fileList.length == 1) {
        document.getElementById('uploadPic').lastChild.style.display = "none"
      } else {
        document.getElementById('uploadPic').lastChild.style.display = "inline-block"
      }
      this.create.temp.businessLicense = -1

       if (fileList.length == 1) {
        this.create.temp.businessLicense = fileList[0].response.execresult.LastInsertId

      }
      console.log(this.create.temp)
    },


    //获取按钮权限
    get_auto_buttons() {
      const Edit = 'ContractApproval'
      const isRoleEdit = checkButtons(JSON.parse(sessionStorage.getItem('buttons')), Edit)
      this.isRoleEdit = isRoleEdit

      const ContractAdopt = 'approval:contract:adopt'
      const isContractAdopt= checkButtons(JSON.parse(sessionStorage.getItem('buttons')), ContractAdopt)
      this.isContractAdopt = isContractAdopt
    },
    //获取所有下拉框的内容
    get_select_list() {

      GetDataByNames(this.send_select_list).then(response => {
        // this.customerNameList = response.data.getCustomerSelect.list
        // console.log("客户名称下拉框", this.houseNameList)
        this.groupNameList = response.data.getDictListSelect.list
        console.log("集团下拉框", this.groupNameList)

        this.createrNameList = response.data.getUsersSelect.list
        console.log("创建人下拉框", this.createrNameList)


        response.data.getProductsEnable.list.map(function (i) {
          return (i.customerId = "")
        })
        response.data.getProductsEnable.list.map(function (i) {
          return (i.nums = "")
        })
        response.data.getProductsEnable.list.map(function (i) {
          return (i.remark = "")
        })
        this.receProductNameList = response.data.getProductsEnable.list
        console.log("收件货品下拉框", this.receProductNameList)


      })

    },
    //加载表格
    get_table_data() {
      var me = this
      this.tableObj.listLoading = true
      console.log("this.tableObj.getdataListParm======>", this.tableObj.getdataListParm)
      GetDataByName(this.tableObj.getdataListParm).then(response => {
        console.log('table数据======>', response.data.list)
        if (response.data.list !== null) {


          for (let i = 0; i < response.data.list.length; i++) {
            var url = process.env.VUE_APP_BASE_API + response.data.list[i].picname1
            this.$set(response.data.list[i], 'imgUrlDetil', url )
          }

          this.tableObj.list = response.data.list
          this.tableObj.pageNum = response.data.pageNum
          this.tableObj.pageSize = response.data.pageSize
          this.tableObj.total = response.data.total


          //计算操作栏宽度
          var btnNum = 0
              var arrList = response.data.list
              arrList.forEach(function(row){
                  var itemBtnNum = 0
                  if(me.roleSet(row)){
                    itemBtnNum = itemBtnNum + 2
                  }


                  console.log(itemBtnNum)
                  if(itemBtnNum > btnNum){
                    btnNum = itemBtnNum
                  }
              })


              console.log("btnNum=============",btnNum)
              me.autoWidth = btnNum * 90  + 90

          console.log('table数据======>', this.tableObj.list)
        } else {
          this.tableObj.list = []
        }
        setTimeout(() => {
          this.tableObj.listLoading = false
        }, 100)
      })


      var send_price = {
        name: 'getContractOfPrice',
        parammaps: this.tableObj.getdataListParm.parammaps
      }

      GetDataByName(send_price).then(response => {
        console.log('table总价格数据======>', response )
        if (response.data.list !== null) {
          this.tableSumMoney = response.data.list[0].totlePrice
        } else {
          this.tableSumMoney = ""
        }
      })


    },
    form_search() {
      console.log('点击了查询')

      if (this.tableObj.getdataListParm.parammaps.inputDatetime1 !== '' && this.tableObj.getdataListParm.parammaps.inputDatetime1 !== null) {
        this.tableObj.getdataListParm.parammaps.beginContractBeginDate = parseTime(this.tableObj.getdataListParm.parammaps.inputDatetime1[0], '{y}-{m}-{d}')
        this.tableObj.getdataListParm.parammaps.endContractBeginDate = parseTime(this.tableObj.getdataListParm.parammaps.inputDatetime1[1], '{y}-{m}-{d}')
      } else {
        this.tableObj.getdataListParm.parammaps.inputDatetime1 = ''
        this.tableObj.getdataListParm.parammaps.beginContractBeginDate = ''
        this.tableObj.getdataListParm.parammaps.endContractBeginDate = ''
      }

      if (this.tableObj.getdataListParm.parammaps.inputDatetime2 !== '' && this.tableObj.getdataListParm.parammaps.inputDatetime2 !== null) {
        this.tableObj.getdataListParm.parammaps.beginContractEndDate = parseTime(this.tableObj.getdataListParm.parammaps.inputDatetime2[0], '{y}-{m}-{d}')
        this.tableObj.getdataListParm.parammaps.endContractEndDate = parseTime(this.tableObj.getdataListParm.parammaps.inputDatetime2[1], '{y}-{m}-{d}')
      } else {
        this.tableObj.getdataListParm.parammaps.inputDatetime2 = ''
        this.tableObj.getdataListParm.parammaps.beginContractEndDate = ''
        this.tableObj.getdataListParm.parammaps.endContractEndDate = ''
      }

      if (this.tableObj.getdataListParm.parammaps.inputDatetime3 !== '' && this.tableObj.getdataListParm.parammaps.inputDatetime3 !== null) {
        this.tableObj.getdataListParm.parammaps.beginCreaterDate = parseTime(this.tableObj.getdataListParm.parammaps.inputDatetime3[0], '{y}-{m}-{d}')
        this.tableObj.getdataListParm.parammaps.endCreaterDate = parseTime(this.tableObj.getdataListParm.parammaps.inputDatetime3[1], '{y}-{m}-{d}')
      } else {
        this.tableObj.getdataListParm.parammaps.inputDatetime3 = ''
        this.tableObj.getdataListParm.parammaps.beginCreaterDate = ''
        this.tableObj.getdataListParm.parammaps.endCreaterDate = ''
      }


      this.tableObj.getdataListParm.offset = 1
      this.get_table_data()
    },
    form_clear() {
      console.log('点击了重置')

      this.tableObj.getdataListParm.parammaps.customerName = ''
      this.tableObj.getdataListParm.parammaps.contractCode = ''
      this.tableObj.getdataListParm.parammaps.customerId = ''
      this.tableObj.getdataListParm.parammaps.groupId = ''

      this.tableObj.getdataListParm.parammaps.contractStatus = ''
      this.tableObj.getdataListParm.parammaps.createrId = ''
      this.tableObj.getdataListParm.parammaps.beginContractMoney = ''
      this.tableObj.getdataListParm.parammaps.endContractMoney = ''
      this.tableObj.getdataListParm.parammaps.beginMoneyStep = ''
      this.tableObj.getdataListParm.parammaps.endMoneyStep = ''

      this.tableObj.getdataListParm.parammaps.inputDatetime1 = ''
      this.tableObj.getdataListParm.parammaps.inputDatetime2 = ''
      this.tableObj.getdataListParm.parammaps.inputDatetime3 = ''

       this.tableObj.getdataListParm.parammaps.beginContractBeginDate = ''
      this.tableObj.getdataListParm.parammaps.endContractBeginDate = ''
      this.tableObj.getdataListParm.parammaps.beginContractEndDate = ''
       this.tableObj.getdataListParm.parammaps.endContractEndDate = ''
      this.tableObj.getdataListParm.parammaps.beginCreaterDate = ''
      this.tableObj.getdataListParm.parammaps.endCreaterDate = ''
      this.tableObj.getdataListParm.offset = 1
      this.get_table_data()


    },

    // 新增
    form_reset() {
      this.create.temp =   {  contractStatus: '',    customerId: '', groupId: '', groupName: '', serviceCode: '', contractBeginDate: parseTime(new Date(), '{y}-{m}-{d}'), contractEndDate: parseTime(new Date(), '{y}-{m}-{d}'), createrId:  Cookies.get('employeid'), createrName:  Cookies.get('employename'),moneyStep: '1',contractMoney: '', businessLicense: -1,picname1: '',userIds:""},

      this.fileList = []

      this.tableStagesList = []
      this.tableStockList = []
       document.getElementById('uploadPic').lastChild.style.display = "inline-block"


    },


    //客户失去焦点
    customer_search_blur(item) {
      console.log("客户失去焦点")
      this.tableObj.getdataListParm.parammaps.customerId = ""
      this.tableObj.getdataListParm.parammaps.customerName = ""
      this.customerNameList = []
    },


    //模糊查询客户
    customer_search(queryString, cb) {
      console.log('模糊查询输入值', queryString)
      GetDataByName({ name: 'getCustomerNameFuzzy', page: 1, offset: 1, pagecount: 10, returntype: 'Map', parammaps: { inputvalue: queryString } }).then(response => {
        this.customerNameList = response.data.list
        console.log("客户名称下拉框", response)
        cb(response.data.list)
      })
    },

    //模糊查询客户选择
    change_customer_select(item) {
      console.log('客户名称模糊查询选中值', item)
      this.tableObj.getdataListParm.parammaps.customerId = item.id
      this.tableObj.getdataListParm.parammaps.customerName = item.name
      this.$forceUpdate()
    },

    //清空客户选择
    clear_customer_select(item) {
      document.activeElement.blur()
      this.tableObj.getdataListParm.parammaps.customerId = ""
      this.tableObj.getdataListParm.parammaps.customerName = ""
    },


    //监听 - 集团
    change_group(item) {
      console.log(item)
      console.log(this.create.temp.groupId)
      this.create.temp.groupId = item
      this.create.getdataListParmCust.parammaps.groupId = item

      this.create.temp.customerName = ""
      this.create.temp.customerId = ""
      this.create.customerNameList = []

      this.get_customer_list()
      this.$forceUpdate()

    },
    // 弹窗中的客户
    get_customer_list() {
      GetDataByName(this.create.getdataListParmCust).then(response => {
        if (response.data.list !== null) {
          this.create.customerNameList = response.data.list
          console.log('弹窗中的客户数据', response.data.list)
        } else {
          this.create.customerNameList = []
        }
      })
    },


    //监听 - 下拉中客户名称
    change_customer(item) {
      console.log(item)
      this.create.temp.customerId = item


    },


    // 款项信息表格
    getStagesTableList() {
      GetDataByName(this.create.getdataListParmStages).then(response => {
        if (response.data.list !== null) {
          this.tableStagesList   = response.data.list
          console.log('款项信息表格数据', response.data.list)
        } else {
          this.tableStagesList = []
        }
      })
    },

    // 备货信息表格
    getStockTableList() {
      GetDataByName(this.create.getdataListParmStock).then(response => {
        if (response.data.list !== null) {
          this.tableStockList  = response.data.list
          console.log('备货信息表格数据', response.data.list)
        } else {
          this.tableStockList  = []
        }
      })
    },


    // 监听 - 下拉 - 款项分期
    change_moneyStep(item) {
      console.log(item)
      var me = this

      var table_len = this.tableStagesList.length


      console.log("table_len",table_len)


      if( item > table_len ){
          var num = parseInt(item) - parseInt(table_len)

             console.log("num",num)
             for(var i=1; i< num+1; i++){
                console.log(i)
                 me.tableStagesList.push({'stages':i+parseInt(table_len),'planCostRate':'','planCost':'','collectionDate': parseTime(new Date(), '{y}-{m}-{d}'),'customerId':'','createrId':''})
             }


      }


      if( item < table_len ){


        var arrTemp = me.tableStagesList.slice(0, item)

        me.tableStagesList = arrTemp

      }


    },


    //下拉 - 备货品
    change_receProduct(item) {
      console.log("备货品ID ", item)
      var index = this.receProductNameList.findIndex(obj => obj.productsId == item)
      console.log("备货品index ", index)
      var ifHasId = this.tableStockList.findIndex(obj => obj.productsId == item)
      console.log("备货品是否存在列表 ", ifHasId)

      var addRow = Object.assign({}, this.receProductNameList[index])
      addRow.nums = 1
      addRow.remark = ""
      if (ifHasId == "-1") {
        this.tableStockList.unshift(addRow)
      }

    },


    // 查看
    form_see(row) {


      // this.form_reset()


      this.conmoreData.id = row.id

      this.create.temp.id = row.id

      this.create.temp.contractStatus = row.contractStatus

      this.create.temp.userIds = row.userIds


      console.log('点击了查看',row)


      // 现场照片
      const urlArray = []
      const urlArrayId = []
      const fileList = []

      if (this.create.temp.picname1 != undefined) {
        urlArray.push(process.env.VUE_APP_BASE_API + this.create.temp.picname1)
        urlArrayId.push(this.create.temp.businessLicense)
      }


      console.log("urlArray", urlArray)
      console.log("urlArrayId", urlArrayId)


      for (let i = 0; i < urlArray.length; i++) {
        var urlObj = { "url": "", "response": { "execresult": { "LastInsertId": "" } } }
        urlObj.url = urlArray[i]
        // this.$set(urlObj, 'url', urlArray[i])
        // this.$set(urlObj, 'response', 15)
        urlObj.response.execresult.LastInsertId = urlArrayId[i]
        fileList.push(urlObj)
      }

      this.fileList = fileList

      console.log("fileList", fileList)


      this.createSee.dialogFormVisible = true


    },


    // 通过
    form_adopt(row) {
      console.log('点击了通过', row)
      this.reset_adopt()

      this.adopt.temp.id = row.id
      this.adopt.temp.contractStatus = row.contractStatus
      this.adopt.dialogFormVisible = true
    },
    // 通过 - 重置
    reset_adopt() {
      this.adopt.temp.remark = ""
      this.adopt.temp.contractStatus = ""
    },

    // 通过 - 确认
    form_adopt_save() {
      this.$refs['adopttemp'].validate(valid => {
        if (valid) {


          var send_data = {
            "common": {"returnmap": "0"},
            "data": [
              {
                "name": "insertApprovalOfContract","type": "e",
                "parammaps": {
                  "typeName":"合同审批",
                  "objectId":this.adopt.temp.id,
                  "statusId":"1",
                  "remark":this.adopt.temp.remark ,
                  "userId":Cookies.get('employeid'),
                  "stepName":this.adopt.temp.contractStatus
                },
               },

                {
                  "name": "updateContractApprovalSuccess","type": "e",
                  "parammaps": {
                    "id":this.adopt.temp.id,
                    "stepName":this.adopt.temp.contractStatus
                  }
                }

            ]
          }


                 ExecDataByConfig(send_data).then(response => {
                    console.log('通过发送参数', send_data)
                    if (response.msg !== 'fail') {
                      this.$notify({ title: '成功', message: '通过成功', type: 'success', duration: 2000 })
                      this.adopt.dialogFormVisible = false
                      this.create.dialogFormVisible = false
                      this.createSee.dialogFormVisible = false
                      this.conmoreData.id = ""
                      this.get_table_data()


                      var send_weixin_data1 = {
                        name: 'getRemindData',
                        parammaps: {
                          "userId":Cookies.get('g_userId'),
                          "remindId":2,
                          "remindTypeName":'合同',
                          "rowId":this.adopt.temp.id

                        }
                      }
                      if(this.adopt.temp.contractStatus == "一审中"){
                        send_weixin_data1.parammaps.remindId = 2
                      }
                      if(this.adopt.temp.contractStatus == "二审中"){
                        send_weixin_data1.parammaps.remindId = 3
                      }
                      if(this.adopt.temp.contractStatus == "三审中"){
                        send_weixin_data1.parammaps.remindId = 4
                      }
                      GetDataByName(send_weixin_data1).then(response => {
                        console.log('微信推送(获取参数)======>', response )
                        if (response.data.message == 'ok') {
                          var receiverStr = response.data.list[0].receivers
                          var receiverArr = receiverStr.split(',')
                          var value1 = response.data.list[0].value1
                          var value2 = response.data.list[0].value2
                          var value3 = response.data.list[0].value3
                          var value4 = response.data.list[0].value4
                          var send_weixin_data2 = {
                            "target": receiverArr,
                            "serviceId": 2,
                            "content": [
                              { "color": "#173177","value": value1 },
                              { "color": "#173177", "value": value2 },
                              { "color": "#173177", "value": value3 },
                              { "color": "#173177","value": value4 }
                            ]
                          }

                          if(this.adopt.temp.contractStatus == "一审中"){
                            send_weixin_data2.serviceId = 2
                          }
                          if(this.adopt.temp.contractStatus == "二审中"){
                            send_weixin_data2.serviceId = 3
                          }
                          if(this.adopt.temp.contractStatus == "三审中"){
                            send_weixin_data2.serviceId = 4
                          }
                            wxpush(send_weixin_data2).then(response => {
                              console.log('微信推送(获取参数)======>', response )
                            })
                         // this.tableSumMoney = response.data.list[0].totlePrice
                        } else {
                          // this.$notify({ title: '失败', message: '消息推送失败', type: 'error', duration: 2000 })
                        }
                      })


                      if(this.isHome == 'home'){
                      // 返回首页
                         this.$router.push({ name: 'Dashboard', params: { isTodo: 'contractapp' }})
                      }
                    } else {
                      this.$notify({ title: '失败', message: '通过失败' + response.data, type: 'error', duration: 2000 })
                    }
                  })


        }
      })
    },
    form_quick(row){
      var send_weixin_data1 = {
                        name: 'getRemindData',
                        parammaps: {
                          "userId":Cookies.get('g_userId'),
                          "remindId":1,
                          "remindTypeName":'合同',
                          "rowId":row.id

                        }
                      }

                      if(row.contractStatus == "一审中"){
                        send_weixin_data1.parammaps.remindId = 1
                      }
                      if(row.contractStatus == "二审中"){
                        send_weixin_data1.parammaps.remindId = 2
                      }
                      if(row.contractStatus == "三审中"){
                        send_weixin_data1.parammaps.remindId = 3
                      }
                      if(row.contractStatus == "四审中"){
                        send_weixin_data1.parammaps.remindId = 4
                      }
                      if(row.contractStatus == "五审中"){
                        send_weixin_data1.parammaps.remindId = 5
                      }

                      GetDataByName(send_weixin_data1).then(response => {
                        console.log('微信推送(获取参数)======>', response )
                        if (response.data.message == 'ok') {
                          var receiverStr = response.data.list[0].receivers
                          var receiverArr = receiverStr.split(',')
                          var value1 = response.data.list[0].value1
                          var value2 = response.data.list[0].value2
                          var value3 = response.data.list[0].value3
                          var value4 = response.data.list[0].value4
                          var send_weixin_data2 = {
                            "target": receiverArr,
                            "serviceId": send_weixin_data1.parammaps.remindId,
                            "content": [
                              { "color": "#173177","value": value1 },
                              { "color": "#173177", "value": value2 },
                              { "color": "#173177", "value": value3 },
                              { "color": "#173177","value": value4 }
                            ]
                          }


                            wxpush(send_weixin_data2).then(response => {
                              console.log('微信推送(获取参数)======>', response )
                              if(response.msg == "ok"){
                                 this.$notify({ title: '成功', message: '消息提醒成功', type: 'success', duration: 2000 })
                              }
                            })
                         // this.tableSumMoney = response.data.list[0].totlePrice
                        } else {
                          // this.$notify({ title: '失败', message: '消息推送失败', type: 'error', duration: 2000 })
                        }
                      })
    },

    // 驳回
    form_reject(row) {
      console.log('点击了驳回', row)
      this.reset_reject()

      this.reject.temp.id = row.id
      this.reject.temp.contractStatus = row.contractStatus
      this.reject.dialogFormVisible = true
    },
    // 驳回 - 重置
    reset_reject() {
      this.reject.temp.remark = ""
      this.reject.temp.contractStatus = ""
    },

    // 驳回 - 确认
    form_reject_save() {
      this.$refs['rejecttemp'].validate(valid => {
        if (valid) {


          var send_data = {
            "common": {"returnmap": "0"},
            "data": [
              {
                "name": "insertApproval","type": "e",
                "parammaps": {
                  "typeName":"合同审批",
                  "objectId":this.reject.temp.id,
                  "statusId":"0",
                  "remark":this.reject.temp.remark ,
                  "userId":Cookies.get('employeid'),
                  "stepName":this.reject.temp.contractStatus
                },
               },

                {
                  "name": "updateContractApprovalFalse","type": "e",
                  "parammaps": {"id":this.reject.temp.id}
                }

            ]
          }

               console.log(this.reject.temp)

                 ExecDataByConfig(send_data).then(response => {
                    console.log('驳回发送参数', send_data)
                    if (response.msg !== 'fail') {
                      this.$notify({ title: '成功', message: '驳回成功', type: 'success', duration: 2000 })
                      this.reject.dialogFormVisible = false
                      this.create.dialogFormVisible = false
                      this.createSee.dialogFormVisible = false
                      this.conmoreData.id = ""
                      this.get_table_data()


                      var send_weixin_data1 = {
                        name: 'getRemindData',
                        parammaps: {
                          "userId":Cookies.get('g_userId'),
                          "remindId":2,
                          "remindTypeName":'合同',
                          "rowId":this.reject.temp.id

                        }
                      }
                      if(this.reject.temp.contractStatus == "一审中"){
                        send_weixin_data1.parammaps.remindId = 5
                      }
                      if(this.reject.temp.contractStatus == "二审中"){
                        send_weixin_data1.parammaps.remindId = 6
                      }
                      if(this.reject.temp.contractStatus == "三审中"){
                        send_weixin_data1.parammaps.remindId = 7
                      }
                      GetDataByName(send_weixin_data1).then(response => {
                        console.log('微信推送(获取参数)======>', response )
                        if (response.data.message == 'ok') {
                          var receiverStr = response.data.list[0].receivers
                          var receiverArr = receiverStr.split(',')
                          var value1 = response.data.list[0].value1
                          var value2 = response.data.list[0].value2
                          var value3 = response.data.list[0].value3
                          var value4 = response.data.list[0].value4
                          var send_weixin_data2 = {
                            "target": receiverArr,
                            "serviceId": 2,
                            "content": [
                              { "color": "#173177","value": value1 },
                              { "color": "#173177", "value": value2 },
                              { "color": "#173177", "value": value3 },
                              { "color": "#173177","value": value4 }
                            ]
                          }

                          if(this.reject.temp.contractStatus == "一审中"){
                            send_weixin_data2.serviceId = 5
                          }
                          if(this.reject.temp.contractStatus == "二审中"){
                            send_weixin_data2.serviceId = 6
                          }
                          if(this.reject.temp.contractStatus == "三审中"){
                            send_weixin_data2.serviceId = 7
                          }
                            wxpush(send_weixin_data2).then(response => {
                              console.log('微信推送(获取参数)======>', response )
                            })
                         // this.tableSumMoney = response.data.list[0].totlePrice
                        } else {
                          // this.$notify({ title: '失败', message: '消息推送失败', type: 'error', duration: 2000 })
                        }
                      })


                      if(this.isHome == 'home'){
                        // 返回首页
                        this.$router.push({ name: 'Dashboard', params: { isTodo: 'contractapp' }})
                        }
                    } else {
                      this.$notify({ title: '失败', message: '驳回失败' + response.data, type: 'error', duration: 2000 })
                    }
                  })


        }
      })
    },

    dialog_close_see(){
      this.createSee.dialogFormVisible = false
      this.conmoreData.id = ""

      this.get_table_data()
      if(this.isHome == 'home'){
       // 返回首页
       this.$router.push({ name: 'Dashboard', params: { isTodo: 'contractapp' }})
      }
    },

    dialog_close_adopt(){
      this.adopt.dialogFormVisible = false
      this.get_table_data()
      if(this.isHome == 'home'){
       // 返回首页
       this.$router.push({ name: 'Dashboard', params: { isTodo: 'contractapp' }})
      }
    },
    dialog_close_reject(){
      this.reject.dialogFormVisible = false
      this.get_table_data()
      if(this.isHome == 'home'){
       // 返回首页
       this.$router.push({ name: 'Dashboard', params: { isTodo: 'contractapp' }})
      }
    },

    // 导出
    form_export(item) {
      if (item == 1) {
        console.log('点击了导出模板')
      } else {
        console.log('点击了导出数据')
      }
    },

    // 导入
    form_inport() {
      console.log('点击了导入')
    }

  }
}
</script>
<style lang="scss" scoped>
.search {
  padding-top: 10px;
  clear: both;
}
.table {
  margin-top: 10px;
}

#uploadPic {
  width: 700px;
}

// #uploadPic .el-upload-list--picture-card .el-upload-list__item {
//   width: 70px;
//   height: 70px;
// }
// #uploadPic .el-upload--picture-card {
//   width: 70px;
//   height: 70px;
//   line-height: 70px;
// }
// #uploadPic .hide .el-upload--picture-card {
//   display: none;
// }

// // 查看 隐藏删除
// #uploadPicSee {
//   height: 70px;
// }
// #uploadPicSee .el-upload-list--picture-card .el-upload-list__item {
//   width: 70px;
//   height: 70px;
// }
// #uploadPicSee .el-upload--picture-card {
//   width: 70px;
//   height: 70px;
//   line-height: 70px;
// }
// #uploadPicSee
//   .el-upload-list--picture-card
//   .el-upload-list__item-actions
//   .el-upload-list__item-delete {
//   display: none;
// }

/deep/ .el-input.is-disabled .el-input__inner {color: #000000!important;}
/deep/ .el-textarea.is-disabled .el-textarea__inner {color: #000000!important;}
/deep/ .el-radio__input.is-disabled+span.el-radio__label {color: #000000!important;}
/deep/ .el-checkbox__input.is-disabled+span.el-checkbox__label { color: #000000!important;}

</style>
