<template>
  <!--通知供应商盖章页面-->
  <dialog-edit :visible.sync="dialogVisible"
               :title="$t('common.notifySupplierStamp')"
               append-to-body
               :footerBtnShow="isFootView"
               :editModel="'V'"
               :form="form"
               :api="api">
    <!--订单信息-->
    <!--表格-->
    <!--      <div  class="textRight handle-divider-style">-->
    <!--        <el-button size="medium" type="primary" class="iconfont "  @click="loadDown()"> {{$t('traceMgr.downloadingData')}}</el-button>-->
    <!--        <el-button size="medium" type="primary" class="iconfont " :loading="loading"  @click="submit()"> {{$t('common.save')}}</el-button>-->
    <!--      </div>-->
    <!--      <div class="handle-text-margin-bottom title">-->
    <!--        <span   >{{$t('traceMgr.fileListTableName')}}</span>-->
    <!--      </div>-->
    <!--      <el-divider></el-divider>-->
    <!--      -->
    <el-row class="marginBottom4">
      <div  class="textRight handle-divider-style-supplier">
        <btn-batch-download
          :fileID="fileIDs" :beforeBtchDownload="beforeBtchDownload"
          type="primary" size="medium" :downloadButtonMsg="$t('traceMgr.batchDownload')"
          :classType="true"></btn-batch-download>
      </div>
      <!--      <el-tab-pane :label="$t('common.orderInformation')"></el-tab-pane>-->
      <div  class="handle-text-margin-bottom-supplier title">
        <span>{{$t('common.orderInformation')}}</span>
      </div>
      <el-divider></el-divider>
    </el-row>
    <order-list :getSelectRows="getSelectRows" :assetCode="form.param" :supplierId="form.supplierId" :fatherVisible="visible" :ref="'multipleTable'"
                :showSelection="true"></order-list>
    <!--生成话术-->
    <el-row class="text-center">
      <auth-button size="medium" type="primary" :label="$t('traceMgr.createWords')"  @click="getDiscourseView()">
      </auth-button>
    </el-row>

    <el-col  :span="24"  v-show="showDialog">
      <!--已选择订单列表组件-->
      <el-row  class="marginBottom2">

        <h3 class="marginBottom7 title">{{$t('common.contact')}}：
          <span>{{text}}&nbsp;&nbsp;&nbsp;&nbsp;</span>
        </h3>
        <el-divider></el-divider>
      </el-row>
      <el-row>
        <selected-order-list :showDialog="showDialog" :orderParam="selectedRows"  :getSelectRows="getContactRows"  :sourceData="selectedSourceData"></selected-order-list>
      </el-row>
      <el-row class="word_wrap" >
        <el-col :span="1" class="text-center">
          <span>{{$t('traceMgr.wordsTechnique')}}</span>
        </el-col>
        <el-col :span="12">
          <speech-craft-input :autosize="autosize" v-model="content" :defaultSpeechFlag="false" @defaultSpeech="resetSpeechCraft" ></speech-craft-input>
        </el-col>
      </el-row>
      <el-row class="text-center">
        <auth-button  class="finish_bt" type="primary" size="medium" @click="complete" :label="$t('traceMgr.completeInform')"></auth-button>
        <el-button size="medium" @click="dialogVisible=false">{{$t('common.close')}}</el-button>
      </el-row>

    </el-col>
    <dialog-edit :saveLabel="$t('traceMgr.sure')"
                 :closeLabel="$t('approval.cancel')"
                 editModel="E" :form="form"
                 :visible.sync="doSave"
                 appendToBody
                 :loading="isLoading"
                 :title="$t('common.tip')"
                 width="35%"
                 :close-on-click-modal="false"
                 class="el-dialog--center"
                 :autoSave="false"
                 @onSaved="onSaved">
      <p class="text-center padding-content">{{$t('traceMgr.checkConfirm')}}?</p>
    </dialog-edit>
  </dialog-edit>
</template>
<script>
import { DialogEdit, speechCraftInput, btnBatchDownload, DataTable, authButton } from 'newepoch-components'
import OrderList from './orderList'
import SelectedOrderList from './selectedOrderList'
import BasePage from '@/pages/basePage'
import mixin from '@/pages/mixin'
import tracemgrApi from '@/api/tracemgrApi'

export default {
  extends: new BasePage(),
  mixins: [mixin],
  name: 'taskDialog',
  components: {
    DialogEdit,
    authButton,
    tracemgrApi,
    btnBatchDownload,
    speechCraftInput,
    DataTable,
    OrderList,
    SelectedOrderList
  },
  data () {
    return {
      contactList: [],
      fileIDs: [],
      text: '',
      contactSelectedRows: [],
      isLoading: false,
      showDialog: false,
      userInfo: {},
      api: {},
      resultMsg: {
        successMsg: this.$i18n.messages[this.$i18n.locale].common.operationSuccessful,
        failMsg: this.$i18n.messages[this.$i18n.locale].common.operationfail
      },
      selectedRows: [],
      instanceIds: [],
      doSave: false,
      multipleSelection: [],
      sourceData: [],
      selectedSourceData: [],
      autosize: {
        minRows: 8,
        maxRows: 10
      },
      isFootView: false,
      content: '',
      isDiscourseVisible: true
    }
  },
  props: {
    form: { type: Object },
    visible: {
      type: Boolean,
      default: function () {
        return false
      }
    },
    handler: {
      type: Function
    }
  },
  computed: {
    dialogVisible: {
      get: function () {
        return this.visible
      },
      set: function (val) {
        this.$emit('update:visible', val)
      }
    }
  },
  methods: {
    // 完成通知
    onSaved () {
      if (this.selectedRows.length < 1) {
        this.error(this.$i18n.messages[this.$i18n.locale].common.seletedOne)
        return
      }
      let $this = this
      $this.isLoading = true
      let param = []
      this.selectedRows.forEach(item => {
        let obj = {
          taskId: this.form.param[0].taskId,
          assetId: item.paymentConfirmationNumber
        }
        param.push(obj)
      })
      tracemgrApi['supplierSealNotice'].save(this.form.param).then(res => {
        if (res.data) {
          $this.dialogVisible = false
          $this.handler()
          $this.isLoading = false
          $this.isDiscourseVisible = true
          $this.doSave = false
          $this.success($this.resultMsg.successMsg)
        } else {
          $this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.noticeFailure)
          $this.isLoading = false
        }
      }, res => {
        $this.error($this.resultMsg.failMsg)
        $this.isLoading = false
      })
    },
    complete () {
      if (this.selectedRows.length < 1) {
        this.error(this.$i18n.messages[this.$i18n.locale].common.seletedOne)
        return
      }
      this.doSave = true
    },
    getDiscourseView () {
      let $this = this
      let contactarr = this.contactSelectedRows
      if (this.showDialog) {
        this.showDialog = false
        return
      }
      let arr = this.selectedRows
      let status = false
      arr.forEach(item => {
        if (item.takeTheChapterWay === undefined || !(item.takeTheChapterWay === 2 || item.takeTheChapterWay === 1)) {
          $this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.seletedNotNull)
          status = true
        }
      })
      if (status) {
        return
      }
      if (arr.length < 1) {
        this.error(this.$i18n.messages[this.$i18n.locale].common.seletedOne)
        return
      }
      let takeTheChapterWayType = false
      let change = arr[0].takeTheChapterWay
      for (let len = 0; len < arr.length; len++) {
        if (arr[len].takeTheChapterWay !== change) {
          this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.stampTypeSame)
          takeTheChapterWayType = true
        }
      }
      if (takeTheChapterWayType) {
        return
      }
      this.showDialog = true
      if (contactarr.fileId !== undefined) {
        this.fileIDs.push(contactarr.fileId)
      }
      // this.phone=arr.phoneNum
      let varChar = ''
      // 选择订单 根据联系人去重获取联系人
      let uniqueContactarr = this.unique(this.contactList)
      console.log(uniqueContactarr)
      uniqueContactarr.forEach(item => {
        if (item.telephone || item.account) {
          varChar += item.employeeName + '-'
        } else {
          varChar += item.employeeName
        }
        if (item.account) {
          varChar += item.telephone + '-'
        } else {
          varChar += item.telephone
        }
        varChar += item.account + '　'
      })
      this.text = varChar

      this.resetSpeechCraft()
      // this.content
      // this.selectedRows = contactarr
      // 调用接口获取已选择订单数据
    },
    // 选择
    unique (arr) {
      const res = new Map()
      return arr.filter((arr) => !res.has(arr.employeeName) && res.set(arr.employeeName, 1))
    },
    getContactRows (arr) {
      this.contactSelectedRows = arr
    },
    getSelectRows (arr) {
      this.selectedRows = arr
      this.fileIDs = []
      if (arr.length > 0) {
        for (let i = 0; i < arr.length; i++) {
          this.fileIDs.push(arr[i].fileId)
        }
      }
    },
    resetSpeechCraft () {
      let arr = this.selectedRows
      let templete = ''
      let change = arr[0].takeTheChapterWay
      if (change === 1) {
        arr.forEach(item => {
          templete += this.$i18n.messages[this.$i18n.locale].traceMgr.checkConfirmHello
          templete += this.$i18n.messages[this.$i18n.locale].traceMgr.checkConfirmAssetCode + item.paymentConfirmationNumber +
                    this.$i18n.messages[this.$i18n.locale].traceMgr.two + item.nameOfTheContract +
                    this.$i18n.messages[this.$i18n.locale].traceMgr.one + parseFloat(item.theAmountOfFactoring).toFixed(2) +
                    this.$i18n.messages[this.$i18n.locale].traceMgr.end
          templete += this.$i18n.messages[this.$i18n.locale].traceMgr.supplierSealNoticeOne
          templete += this.$i18n.messages[this.$i18n.locale].traceMgr.supplierSealNoticeTwo
          templete += arr[0].account
          templete += this.$i18n.messages[this.$i18n.locale].traceMgr.supplierSealNoticeThere
          templete += this.$i18n.messages[this.$i18n.locale].traceMgr.supplierSealNoticeFour
        })
      } else {
        templete += this.$i18n.messages[this.$i18n.locale].traceMgr.contentHolle
        arr.forEach(item => {
          templete += this.$i18n.messages[this.$i18n.locale].traceMgr.contentOne + item.paymentConfirmationNumber + '　'
          templete += this.$i18n.messages[this.$i18n.locale].traceMgr.contentTwo + item.nameOfTheContract + '　'
          templete += this.$i18n.messages[this.$i18n.locale].traceMgr.contentThere + parseFloat(item.theAmountOfFactoring).toFixed(2) + '　'
          templete += this.$i18n.messages[this.$i18n.locale].traceMgr.contentFour
          templete += this.$i18n.messages[this.$i18n.locale].traceMgr.contentFive
          this.contactSelectedRows.forEach((item, key) => {
            templete += key + '.' + item.fileName + '\n'
          })
          templete += this.$i18n.messages[this.$i18n.locale].traceMgr.content
        })
      }

      templete += this.$i18n.messages[this.$i18n.locale].traceMgr.four
      templete += this.userInfo.nickName
      templete += this.$i18n.messages[this.$i18n.locale].traceMgr.five
      templete += this.$i18n.messages[this.$i18n.locale].traceMgr.six + this.userInfo.mobile
      this.content = templete
    },
    beforeBtchDownload () {
      if (this.selectedRows.length === 0) {
        this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.messageWorning)
        return false
      }
      if (this.fileIDs.length === 0) {
        this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.NotDataOfLoad)
        return false
      }
      return true
    },
    getcontactListData () {
      let $this = this
      let param = ''
      this.form.param.forEach((item, index) => {
        if (index === this.form.param.length - 1) {
          param += item.assetCode
        } else {
          param += item.assetCode + ','
        }
      })
      console.log(param)
      tracemgrApi['onlineAuditTaskDialog'].getEmployeeInfos({ 'assetCode': param }).then(res => {
        console.log(res)
        if (res.data) {
          $this.contactList = res.data
        }
      })
    }
  },
  watch: {
    visible: function (newValue, oldValue) {
      if (newValue) {
        this.$nextTick(() => {
          this.selectedRows = []
          this.contactSelectedRows = []
          let param = []
          this.form.param.forEach(item => {
            param.push(item.assetCode)
          })
          tracemgrApi['orderTrackApi'].getPhone().then(info => {
            this.userInfo = info.data
          }, res => {
            this.error(this.$i18n.messages[this.$i18n.locale].traceMgr.getUserInfoFial)
          })
          this.getcontactListData()
          // 调用接口获取数据
          // tracemgrApi['supplierSealNotice'].getTalkingSkill().then(res => {
          //   that.content = res.data
          // })
          this.isDiscourseVisible = true
        })
      } else {
        this.showDialog = false
      }
    }
  },
  mounted: function () {
  }
}
</script>

<style scoped lang="scss">
  @import '~@/styles/tracemgr/factoringCommissioner/taskTable/supplierSealNotice/taskDialog.scss';
</style>
