<template>
  <div>
    <el-form :model="{localRemeteDatasourceData}" :rules="tableRules" ref="monitorForm">
      <data-table :menuFlag="false" :toolMenuFlag="true" :columns="[]" :showPage="false"
                  :operateBtnLayout="''" :sourceData="localRemeteDatasourceData"
                  :showSelection="true" :selectedRows.sync="selectedRows">
        <el-table-column :align="item.align"  v-for="(item) in componentList" :key="item.label"
                                      :label="item.label">
          <template slot-scope="scope">
            <span v-if="scope.row.employeeId && item.prop !== 'isOneFlag'">{{item.format ? item.format(scope.row) : scope.row[item.prop]}}</span>
<!--            :disabled="switchdisable(scope.row)"-->
            <el-switch v-else-if="item.prop === 'isOneFlag'"
                       :active-value="true"
                       :disabled="switchdisable(scope.row)"
                       :inactive-value="false"
                       v-model="scope.row[item.prop]" @change="switchChange(arguments, scope.$index)"></el-switch>
            <el-form-item v-else :prop="'localRemeteDatasourceData.' + scope.$index + '.' + item.prop" :rules="tableRules[item.prop]">
              <component :is="item.component" v-model="scope.row[item.prop]"
                         :dictTypeCode="item.dictTypeCode" :disabled="item.prop === 'account' && scope.row.isDisabled"
                         :maxlength="item.maxlength" :clearable="item.clearable"
                         @selectChanged="selectChanged(arguments, scope.$index)" :name="item.name"
                         :defalutQueryParas ="item.queryParas?item.queryParas():{}"
                         :allowCreate="item.allowCreate">{{item.component==='span'?item.format(scope.row):''}}</component>
<!--              :reload="item.reload ? item.reload(scope.row) : false"-->
            </el-form-item>
          </template>
        </el-table-column>
        <template slot="headButton">
          <div class="float-right">
            <auth-button class="iconfont" :label="$t('common.create')" icon="iconfont iconxinzeng"
                         :menuCode="menuCode" perms="areaAdd" :openPerms="true"
                         size="small" type="primary" @click="createItem"></auth-button>
            <auth-button class="iconfont" size="small" :label="$t('common.del')" icon="iconfont iconshanchu"
                         :menuCode="menuCode" perms="areadel" :openPerms="true"
                         @click="deleteItem" type="danger"></auth-button>
            <auth-button class="iconfont" size="small" :label="$t('common.save')" icon="iconfont iconbaocun11"
                         :menuCode="menuCode" perms="areaSave" :openPerms="true" :loading="saveLoading"
                         @click="saveItem" type="primary"></auth-button>
            <auth-button class="iconfont" size="small" :label="$t('ladingNoticeHandle.contactsDetails')" icon="iconfont iconzuopintoupiao"
                         :menuCode="menuCode" perms="areashowContacts" :openPerms="true"
                         @click="showItem" type="primary"></auth-button>
<!--            <auth-button class="iconfont" size="small" :label="$t('ladingNoticeHandle.firstContactSet')" icon="iconfont iconpiliangshezhichanpinxinxi"-->
<!--                         :menuCode="menuCode" perms="areasetContacts" :openPerms="true"-->
<!--                         @click="settingItem" type="primary"></auth-button>-->
          </div>
          <div class="float-left">
            <!--区域-->
            <el-form-item :label="$t('ladingNoticeHandle.region')" class="margin-bottom2px lineBlock">
              <el-input v-model="localData.expressNumber" :clearable="true" :disabled="true"></el-input>
            </el-form-item>
          </div>
        </template>
      </data-table>
    </el-form>
    <el-row>
      <el-col :sm="12">
        <!--话术-->
        <el-form-item :label="$t('ladingNoticeHandle.speechCraft')" prop="speechCraft" label-width="100px" class="margin-bottom2px">
          <el-input type="textarea" :autosize="{ minRows: 4, maxRows: 5}" v-model="localData.speechCraft"></el-input>
        </el-form-item>
      </el-col>
      <el-col :sm="11">
        <el-form-item class="marginLeft">
          <auth-button class="copy" size="small" :label="$t('ladingNoticeHandle.onekeyCopy')"
                       :menuCode="menuCode" perms="areacopy" :openPerms="true"
                       @click="copy" type="primary"></auth-button>
          <br/>
          <auth-button size="small" :label="$t('ladingNoticeHandle.resetCraft')"
                       :menuCode="menuCode" perms="areadefaultTalk" :openPerms="true"
                       @click="defaultSpeech" type="primary"></auth-button>
        </el-form-item>
      </el-col>
    </el-row>
    <!--表格-->
    <el-form :rules="formRules" ref="check" :model="localData.locallocalData">
      <dym-form :componentList="componentList2" :formValue="localData.locallocalData" @selectChanged="selectChanged1"></dym-form>
    </el-form>
    <del-hint-edit :visible.sync="showDelInfo" :form="item" :editModel="'E'" :delStatus="false" @delSuccess="refinish"></del-hint-edit>
  </div>
</template>

<script>
import { dymForm, DataTable, authButton, SelectDictionary, validate } from 'newepoch-components'
import InputInterval from '@/components/element/shouji/InputInterval'
import ladingNoticeHandleApi from '@/api/shouji/ladingNoticeHandleApi'
import { regExp } from '@/validator/index'
// import componentsApi from '@/api/componentsApi'
import * as format from '@/filters/index'
import ClipBoard from 'clipboard'
import SelectAccount from '@/components/element/shouji/SelectAcount'
// import SelectAccount from '@/components/element/enterpriseInfoManage/SelectAccount.vue'
import ladingNoticeManageApi from '@/api/shouji/ladingNoticeManageApi'
import DelHintEdit from '@/pages/shouji/ladingHandle/delEnterpriseEdit.vue'
export default {
  name: 'handleInfoTabOne',
  components: {
    DelHintEdit,
    dymForm,
    DataTable,
    authButton,
    SelectDictionary,
    InputInterval
  },
  props: {
    menuCode: {
      type: String,
      default: null
    },
    localData: {
      type: Object,
      default () {
        return {}
      }
    }
  },
  data () {
    return {
      selectedRows: [],
      showDelInfo: false,
      item: {},
      saveLoading: false,
      localRemeteDatasourceData: [],
      componentList: [
        // 姓名
        {
          prop: 'employeeName',
          align: 'left',
          clearable: true,
          width: '143px',
          component: 'el-input',
          label: this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.fullName
        },
        // 手机号
        {
          label: this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.phoneNumber,
          prop: 'telephone',
          align: 'left',
          maxlength: 11,
          name: 'telephone',
          clearable: true,
          component: 'el-input'
        },
        // 微信号
        {
          label: this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.wechatNumber,
          prop: 'weixin',
          align: 'left',
          name: 'weixin',
          maxlength: 30,
          clearable: true,
          component: 'el-input'
        },
        // 第一联系人标识
        {
          label: this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.firstPersonMark,
          prop: 'isOneFlag',
          align: 'center',
          component: 'el-switch'
        },
        // 是否生成账号
        {
          label: this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.isCreateAcount,
          prop: 'isGenerateAccount',
          align: 'center',
          component: SelectDictionary,
          dictTypeCode: 'ZD0003',
          clearable: false,
          name: 'isGenerateAccount',
          format: (row) => {
            return format.formatDict(row.isGenerateAccount, 'ZD0003')
          }
        },
        // 联系人账号
        {
          label: this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.contactAccount,
          prop: 'account',
          align: 'center',
          clearable: true,
          // reload: (row) => {
          //   return row.acountReload
          // },
          component: SelectAccount,
          queryParas: () => {
            let temp = { areaId: this.localData.keyId === undefined ? '' : this.localData.keyId }
            // console.log(temp)
            return temp
            // let temp = { enterpriseId: this.localData.keyId === undefined ? '' : this.localData.keyId, enterpriseType: '61', employeeAccountType: '1' }
            // return temp
          },
          name: 'account',
          allowCreate: true
        }
      ],
      componentList2: [
        // 是否提单
        {
          value: 'ifLading',
          label: this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.ifLading,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseSelect,
          clearable: true,
          prop: 'ifLading',
          name: 'ifLading',
          componentName: 'SelectDictionary',
          cols: [8, 8, 8, 8],
          labelWidth: '100px',
          dictTypeCode: 'ZD0003'
        },
        // 预计提单时间
        {
          value: 'ladingTime',
          label: this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.ladingTime,
          clearable: true,
          startPlaceholder: this.$i18n.messages[this.$i18n.locale].common.startDate,
          endPlaceholder: this.$i18n.messages[this.$i18n.locale].common.endDate,
          prop: 'ladingTime',
          name: 'ladingTime',
          type: 'daterange',
          defaultTime: ['00:00:00', '23:59:59'],
          // format: 'timestamp',
          componentName: 'el-date-picker',
          cols: [8, 8, 8, 8],
          labelWidth: '110px'
        },
        // 预计提单金额
        {
          value: 'ladingMoney',
          label: this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.ladingMoneywan,
          placeholder: this.$i18n.messages[this.$i18n.locale].common.pleaseInput,
          clearable: true,
          prop: 'ladingMoney',
          name: 'ladingMoney',
          maxlength: [14, 14],
          componentName: InputInterval,
          cols: [8, 8, 8, 8],
          labelWidth: '150px'
        }
      ],
      formRules: {
        ladingTime: [
          { type: 'array', required: false, message: this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.pleaseRequiredLabel, trigger: 'change' }
        ],
        ladingMoney: [
          { type: 'array', required: false, message: this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.pleaseRequiredAccountLabel, trigger: 'change' },
          { validator: this.yuanValidate, trigger: 'blur' }
        ]
      },
      tableRules: {
        telephone: [
          { required: true, message: this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.employeePhoneInput, trigger: 'change' },
          { validator: validate.mobilePhoneValidate, trigger: 'change' }
        ],
        weixin: [
          { required: true, message: this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.employeeWechatInput, trigger: 'change' },
          { validator: validate.weChatValidate, trigger: 'change' }
        ],
        employeeName: [
          { required: true, message: this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.employeeNameInput, trigger: 'change' },
          { validator: validate.nameValidate, trigger: 'change' }
        ]
      }
    }
  },
  methods: {
    switchChange (value, index) {
      let contactLevel = value[0] ? '1' : '2'
      let you = this.localRemeteDatasourceData[index]
      if (you) {
        let a = []
        let { accountId, employeeId } = you
        a.push({ accountId, employeeId, contactLevel })
        if (a.length > 0) {
          this.$nextTick(() => {
            this.localRemeteDatasourceData = []
          })
          ladingNoticeManageApi.emploeeOper.modifyEmployeeLevel(a).then(res => {
            this.$nextTick(() => {
              this.$emit('getList')
            })
            if (contactLevel === '2') {
              this.success(this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.cancelFirstContactSetSuccess)
            } else {
              this.success(this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.firstContactSetSuccess)
            }
          })
        }
      }
    },
    // selectTable (row, index) {
    //   return !!row.accountId
    // },
    yuanValidate (rule, value, callback) {
      if (value) {
        if (this.localData.locallocalData && this.localData.locallocalData.ifLading && this.localData.locallocalData.ifLading.toString() === '1') {
          if (this.UtilJs.isEmpty(value[0]) && this.UtilJs.isEmpty(value[1])) {
            return callback(new Error(this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.requiredLabel))
          }
        }
        if ((this.UtilJs.isEmpty(value[0]) && !this.UtilJs.isEmpty(value[1])) || (!this.UtilJs.isEmpty(value[0]) && this.UtilJs.isEmpty(value[1]))) {
          callback(new Error(this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.yuanValidateOne))
        }
        if (this.UtilJs.isEmpty(value[0]) || regExp.yuan.test(value[0])) {
          return callback()
        } else {
          callback(new Error(this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.predictLadingAmounttip))
        }
        if (this.UtilJs.isEmpty(value[1]) || regExp.yuan.test(value[1])) {
          return callback()
        } else {
          callback(new Error(this.$i18n.messages[this.$i18n.locale].ladingNoticeManage.predictLadingAmounttip))
        }
      } else {
        return callback()
      }
    },
    // 新增表格
    createItem () {
      let temp = this.localRemeteDatasourceData
      this.localRemeteDatasourceData.push({ isOneFlag: false, idx: temp.length, isGenerateAccount: '0' })
    },
    // 删除表格数据
    deleteItem () {
      if (this.selectedRows.length > 0) {
        let employeeIds = []
        let employeeIdsEx = []
        this.selectedRows.forEach(it => {
          if (it.employeeId) {
            employeeIds.push(it.employeeId)
          } else {
            employeeIdsEx.push(it.idx)
          }
        })
        if (employeeIdsEx.length > 0) {
          this.localRemeteDatasourceData = this.localRemeteDatasourceData.filter(it => {
            return !employeeIdsEx.some(it1 => {
              return it1 === it.idx
            })
          })
        }
        if (employeeIds.length > 0) {
          this.item = { employeeId: employeeIds }
          this.showDelInfo = true
        }
      } else {
        this.warning(this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.pleaseDeleteData)
      }
    },
    // 保存行数据
    saveItem () {
      this.$refs['monitorForm'].validate((valid) => {
        if (valid) {
          let a = []
          let b = []
          let t = this.localRemeteDatasourceData
          t.forEach(it => {
            if (!it.employeeId) {
              a.push(it)
            } else {
              b.push(it)
            }
          })
          a.forEach(it => {
            it.userName = this.$store.state.user.user.userName
            it.areaId = this.localData.keyId
            it.areaName = this.localData.expressNumber
            it.enterpriseId = this.localData.enterpriseId
            it.enterpriseName = this.localData.enterpriseName
            it.coreEnterpriseId = this.localData.enterpriseId
            it.coreEnterpriseName = this.localData.enterpriseName
            it.isOneFlag = it.isOneFlag ? '1' : '2'
            it.isGenerateAccount = it.isGenerateAccount.length === 0 ? '0' : it.isGenerateAccount
            it.tagCode = '61'
          })
          let flag = true
          let temp1 = b.length === 0 ? b : b.filter(it => {
            return a.some(it1 => it.employeeName === it1.employeeName && it.telephone === it1.telephone && it.weixin === it1.weixin)
          })
          flag = temp1.length === 0
          a.forEach(it => {
            if (a.filter(it1 => {
              return it.employeeName === it1.employeeName && it.telephone === it1.telephone && it.weixin === it1.weixin
            }).length > 1) {
              flag = false
            }
          })
          if (!flag) {
            return this.warning(this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.addemployeeNameCheck)
          }
          if (a.length > 0) {
            this.saveEmploeey(a)
          }
        } else {
          this.warning(this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.dataInputNoOk)
        }
      })
    },
    // 保存联系人
    saveEmploeey (data) {
      this.saveLoading = true
      ladingNoticeManageApi.emploeeOper.addEmployeeCollect(data).then(res => {
        this.$emit('getList')
        this.success(this.$i18n.messages[this.$i18n.locale].common.saveSuccess)
      }).finally(res => {
        this.saveLoading = false
      })
    },
    // 查看联系人
    showItem () {
      if (this.selectedRows.length === 1) {
        if (this.selectedRows[0].accountId && this.selectedRows[0].accountId.length > 0) {
          this.$emit('showItem', this.selectedRows[0].accountId, this.selectedRows[0].employeeId)
        } else {
          this.warning(this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.pleaseOkEmploeeyInfo)
        }
      } else if (this.selectedRows.length > 1) {
        this.warning(this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.pleaseOneEmploeeyInfo)
      } else {
        this.warning(this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.pleaseSelectEmploeeyInfo)
      }
    },
    refinish () {
      this.$emit('getList')
    },
    // 设置第一联系人
    settingItem () {
      let you = this.selectedRows.filter(it => it.accountId)
      if (this.selectedRows.length === 1) {
        if (you.length !== 1) {
          this.warning(this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.accountErrorNoSetting)
          return
        }
        let a = []
        you.forEach(it => {
          let { accountId, employeeId } = it
          a.push({ accountId, employeeId })
        })
        if (a.length > 0) {
          ladingNoticeManageApi.emploeeOper.modifyEmployeeLevel(a).then(res => {
            this.$emit('getList')
            this.success(this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.firstContactSetSuccess)
          })
        }
        // this.$refs.dataTable.toggleSelection()
      } else {
        this.warning(this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.onlyOne)
      }
    },
    changeV (prop, index) {
      // if (prop === 'telephone') {
      //   this.localRemeteDatasourceData[index].telephone = this.localRemeteDatasourceData[index].telephone.substr(0, 11)
      // }
      if (prop === 'weixin') {
        this.localRemeteDatasourceData[index].weixin = this.localRemeteDatasourceData[index].weixin.substr(0, 30)
      }
    },
    // datatable改变
    selectChanged (val, index) {
      if (val[1] === 'isGenerateAccount' && val[2]) {
        this.$set(this.localRemeteDatasourceData[index], 'isDisabled', val[0] === '1')
      }
      if (val[1] === 'account' && val[2]) {
        this.localRemeteDatasourceData.forEach(it => {
          if (it.account === val[0]) {
            it.relAccountId = val[2].accountId
            it.account = val[2].account
          }
        })
      }
    },
    // dymfrom改变
    selectChanged1 (key, value) {
      let keyList = Object.keys(key)
      if (keyList.some(it => it === 'ifLadingInfo')) {
        if (!this.localData.locallocalData.ladingTime) {
          this.$set(this.localData.locallocalData, 'ladingTime', ['', ''])
        }
        value = value | (!key.ifLadingInfo ? '' : key.ifLadingInfo.dictId)
        let formRulesList = Object.keys(this.formRules)
        formRulesList.forEach(it1 => {
          if (value.toString() === '1') {
            this.$set(this.formRules[it1][0], 'required', true)
          } else {
            this.$set(this.formRules[it1][0], 'required', false)
            if (this.$refs.check) {
              this.$refs.check.clearValidate()
            }
          }
          // this.formRules[it1].forEach((it2, index) => {
          // })
        })
      }
    },
    // 复制话术
    copy () {
      let copyText = this.localData.speechCraft
      if (copyText.length === 0) {
        return this.error(this.$i18n.messages[this.$i18n.locale].ladingNoticeHandle.noCopy)
      }
      let clipboard = new ClipBoard('.copy', {
        text: function () {
          return copyText
        }
      })
      clipboard.on('success', e => {
        this.success(this.$i18n.messages[this.$i18n.locale].common.copySuccess)
        // 释放内存
        clipboard.destroy()
      })
      clipboard.on('error', e => {
        // 不支持复制
        this.error(this.$i18n.messages[this.$i18n.locale].common.copyFail)
        // 释放内存
        clipboard.destroy()
      })
    },
    // 默认话术
    defaultSpeech () {
      let $this = this
      ladingNoticeHandleApi.messageTemplate.getMessageTemplateApi({ eventType: 'ladingHandle', templateCode: '10' }).then(res => {
        if (res.data && res.data.templateContent) {
          $this.$set($this.localData, 'speechCraft', res.data.templateContent)
        }
      })
    },
    InitData () {
      if (this.localData.locallocalData && this.localData.locallocalData.ifLading) {
        this.selectChanged1({ ifLadingInfo: {} }, this.localData.locallocalData.ifLading)
      }
      this.localRemeteDatasourceData = []
      this.localData.localRemeteDatasourceData.forEach((it, index) => {
        let contactLevel = it.contactLevel ? it.contactLevel : ''
        let employeeName = ''
        let telephone = ''
        let weixin = ''
        let employeeId = ''
        if (it.employeeDTO) {
          employeeName = it.employeeDTO.employeeName ? it.employeeDTO.employeeName : ''
          telephone = it.employeeDTO.telephone ? it.employeeDTO.telephone : ''
          weixin = it.employeeDTO.weixin ? it.employeeDTO.weixin : ''
          employeeId = it.employeeDTO.keyId ? it.employeeDTO.keyId : ''
        }
        let account = ''
        let accountId = ''
        let AccountEmployeeId = ''
        if (it.enterpriseAccountDTO) {
          account = it.enterpriseAccountDTO.account ? it.enterpriseAccountDTO.account : ''
          AccountEmployeeId = it.enterpriseAccountDTO.employeeId ? it.enterpriseAccountDTO.employeeId : ''
          accountId = it.accountId ? it.accountId : ''
        }
        this.localRemeteDatasourceData.push({
          idx: index,
          accountId: accountId,
          employeeId: employeeId,
          isOneFlag: contactLevel.toString() === '1',
          employeeName: employeeName,
          telephone: telephone,
          weixin: weixin,
          isGenerateAccount: account.length === 0 ? '0' : AccountEmployeeId === employeeId ? '1' : '0',
          account: account
        })
      })
    }
  },
  computed: {
    switchdisable () {
      // /*!!data.isOneFlag*/
      return (data) => {
        if (!data.accountId || data.accountId.length === 0) return true
        else return false
      }
    }
  },
  watch: {
    localData: {
      deep: true,
      immediate: true,
      handler (n, o) {
        if (n) {
          if (this.localData.keyId !== n.keyId) {
            this.accountQueryParas = Object.assign({}, { areaId: this.localData.keyId })
          }
          this.InitData()
        }
      }
    }
    // 'localRemeteDatasourceData.telephone' (n, o) {
    //   if (n.length > 11) {
    //     this.localRemeteDatasourceData.telephone = this.localRemeteDatasourceData.telephone.substr(0, 12)
    //   }
    // }
  }
}
</script>

<style scoped lang="scss">
  @import '~@/styles/sj/ladingHandle/handleInfoTabOne.scss';
</style>
