<template>
  <el-dialog
    title="配置"
    :visible.sync="isShowDialog"
    :before-close="handleClose"
    append-to-body
    :close-on-click-modal="false"
    top="5vh"
  >
    <el-tabs v-model="activeName" type="card" @tab-click="handleClick">
      <el-tab-pane label="通讯录同步配置" name="addressBook">
        <el-form
          :model="addressForm"
          v-form="{formItemAlign: 'left'}"
          label-width="140px"
          class="address-form"
          data-vv-scope="configurationForm"
        >
          <ht-form-item label="是否同步组织架构">
            <el-radio-group v-model="addressForm.syncFlag">
              <el-radio :label="true">是</el-radio>
              <el-radio :label="false">否</el-radio>
            </el-radio-group>
          </ht-form-item>
          <template v-if="addressForm.syncFlag">
            <ht-form-item label="同步范围">
              <el-select v-model="addressForm.syncScope" placeholder="请选择">
                <el-option
                  v-for="item in syncScopeOptions"
                  :key="item.key"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </ht-form-item>
            <ht-form-item
              label="选择部门"
              v-if="addressForm.syncScope === 2"
            >
              <tree-Select
                v-if="addressForm.syncDirection === 0"
                v-model="addressForm.syncOrgId"
                :normalizer="normalizer"
                :multiple="false"
                :options="treeData"
                noOptionsText="正在获取第三方组织树..."
                noChildrenText=" "
                placeholder="请选择部门"
                @select="selectOrg"
                :show-count="true"
                append-to-body
                z-index="9999">
                <div slot="value-label" slot-scope="{ node }">{{ getSyncOrgName(node.label) }}</div>
              </tree-Select>
              <ht-org-selector-input
                v-else
                v-model="addressForm.syncOrg"
                :config="{id: 'addressForm.syncOrgId'}"
                append-to-body
                single
              />

            </ht-form-item>
            <ht-form-item label="同步方式">
              <el-radio-group v-model="addressForm.syncDirection" @change="onSyncDirectionChanged">
                <el-radio :label="0">拉取</el-radio>
                <el-radio :label="1">上传</el-radio>
              </el-radio-group>
            </ht-form-item>
            <ht-form-item label="同步方法">
              <el-radio-group v-model="addressForm.autoSync">
                <el-radio :label="true" v-show="false">自动</el-radio>
                <el-radio :label="false">手动</el-radio>
              </el-radio-group>
            </ht-form-item>
            <template v-if="addressForm.autoSync">
              <ht-form-item label="同步频率">
                <el-select
                  v-model="addressForm.syncFrequency"
                  placeholder="请选择"
                >
                  <el-option
                    v-for="item in syncFrequencyOptions"
                    :key="item.label"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
                <ul class="week" v-if="addressForm.syncFrequency === 0">
                  <li
                    class="week-item"
                    :class="{'is-active-item': currentWeek === key}"
                    v-for="(value, key) in weekMap"
                    :key="key"
                    @click="handleClickWeek(key)"
                  >
                    {{ value }}
                  </li>
                </ul>
                <div>
                  <el-date-picker
                    v-if="addressForm.syncFrequency === 1"
                    v-model="selectDate"
                    type="date"
                    placeholder="请选择"
                  >
                  </el-date-picker>
                </div>
              </ht-form-item>
              <ht-form-item
                label="同步起始时间"
                v-if="addressForm.syncFrequency !== 2"
              >
                <el-time-picker
                  v-model="addressForm.syncStartingTime"
                  placeholder="请选择时间"
                >
                </el-time-picker>
              </ht-form-item>
            </template>
          </template>
        </el-form>
      </el-tab-pane>
      <el-tab-pane label="产品应用配置" name="product">
        <product-app-form
          :app-type="appType"
          :productAppForm="addressForm"
          form-scope="configurationForm"
        ></product-app-form>
      </el-tab-pane>
      <el-tab-pane label="第三方应用配置" name="thirdParty" hidden v-if="false">
        <ht-table
          :data="tableData"
          :pageResult="pageResult"
          :selection="false"
          :show-export="false"
          :show-custom-column="false"
          ref="htTable"
          @load="loadData"
        >
          <template v-slot:toolbar>
            <el-button type="primary" @click="handleAddApp" icon="el-icon-plus">添加应用</el-button>
          </template>
          <template>
            <ht-table-column property="agentName" label="应用名称">
              <template v-slot="{row}">
                <el-link
                  type="primary"
                  @click="showDialog(row.id)"
                  title="查看详情"
                  >{{ row.agentName }}</el-link
                >
              </template>
            </ht-table-column>
            <ht-table-column
              prop="alias"
              label="应用别名"
              :show-overflow-tooltip="true"
            >
            </ht-table-column>
            <ht-table-column
              prop="agentId"
              label="AgentId"
              :show-overflow-tooltip="true"
            >
            </ht-table-column>
            <ht-table-column
              prop="agentKey"
              label="应用key"
              :show-overflow-tooltip="true"
              v-if="appType == 'dingtalk'"
            >
            </ht-table-column>
            <ht-table-column
              prop="agentSecret"
              label="应用secret"
              :show-overflow-tooltip="true"
            >
            </ht-table-column>
            <ht-table-column
              prop="menuName"
              label="菜单名称"
              :show-overflow-tooltip="true"
              v-if="appType == 'weChatWork'"
            >
            </ht-table-column>
            <ht-table-column
              prop="menuUrl"
              label="菜单URL"
              :show-overflow-tooltip="true"
            >
            </ht-table-column>
            <ht-table-column
              prop="createTime"
              label="创建时间"
              :show-overflow-tooltip="true"
            >
            </ht-table-column>
          </template>
        </ht-table>
        <el-dialog 
          :visible.sync="appDetailDialog" 
          :title="currentTitle"
          width="30%"
          append-to-body
          :before-close="handleCloseAppDetailDialog"
        >
          <product-app-form
          :app-type="appType"
          ref="productAppForm"
          form-scope="thirdPartyAppForm"
        ></product-app-form>
        <span slot="footer" class="dialog-footer">
          <el-button @click="handleCloseAppDetailDialog">取 消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
        </el-dialog>
      </el-tab-pane>
    </el-tabs>
    <div slot="footer" class="dialog-footer">
      <el-button @click="handleClose">{{ $t('eip.common.cancel') }}</el-button>
      <el-button type="primary" @click="submitForm">{{ $t('eip.common.save') }}</el-button>
    </div>
  </el-dialog>
</template>

<script>
import req from '@/request.js'
import {SYNC_FREQUENCY_OPTIONS, SYNC_SCOPE_OPTIONS, WEEK_MAP} from './const'
import ProductAppForm from './ProductAppForm.vue'
import '@riophae/vue-treeselect/dist/vue-treeselect.css'

const eipOrgSelector = () => import('@/components/selector/EipOrgSelector.vue')
const treeSelect = () => import('@riophae/vue-treeselect')
export default {
  name: 'Configuration',
  components: {
    ProductAppForm,
    eipOrgSelector,
    treeSelect,
  },
  props: {
    isShowDialog: {
      type: Boolean,
      default: false
    },
    appType: String,
    addressForm:{},
    cancelConfig:{},
    treeData: {
      type: Array,
      default: () => ([])
    },
  },
  data() {
    return {
      activeName: 'addressBook',
      selectDate: '',
      syncFrequencyOptions: SYNC_FREQUENCY_OPTIONS,
      syncScopeOptions: SYNC_SCOPE_OPTIONS,
      departmentOptions: [],
      weekMap: WEEK_MAP,
      currentWeek: '',
      pageResult: {
        page: 1,
        pageSize: 10,
        total: 0
      },
      tableData: [],
      appDetailDialog:false,
      currentTitle:'添加应用',
    }
  },

  methods: {
    submitForm() {
      this.$root.$validator.validateAll('configurationForm').then(result=>{
        if(result){
          req.post(this.saveSysExternalUnite(), this.addressForm).then(response => {
            if (response.data && response.data.state) {
              this.$message.success(response.data.message || "操作成功");
              this.afterSaveData()
            } else {
              this.$message.warning(response.data.message || "操作失败");
            }
          })
        } else {
          let arr = this.$validator.errors.items.filter(
              (item) => item.scope == 'configurationForm'
            )
            let errorLength = arr.length
            this.$message({
              showClose: true,
              message: `有${errorLength}个字段未通过校验，请正确填写表单内容。`,
              type: 'warning',
            })
          this.activeName = 'product'
        }
      })
    },
    getSyncOrgName(label){
      if (label && label.lastIndexOf("unknown") > -1) {
      //当treeselect翻译不了值时，获取上次保存的组织名称
        return this.addressForm.syncOrg;
      } else {
        return label;
      }
    },
    onSyncDirectionChanged(){
      this.$set(this.addressForm, 'syncOrgId', null)
      this.$set(this.addressForm, 'syncOrg', null)
    },
    normalizer(node) {
      if (node.children && !node.children.length) {
        delete node.children;
      }
      return {
        id: node.id,
        label: node.name,
        children: node.children,
        isDefaultExpanded: false,
      }
    },
    selectOrg(node){
      this.$set(this.addressForm, 'syncOrgId', node.id)
      this.$set(this.addressForm, 'syncOrg', node.name)
    },
    afterSaveData() {
      this.$emit('update:isShowDialog', false)
    },
    edit(val){
      console.log(val)
    },
    saveSysExternalUnite: function() {
      return window.context.portal + '/portal/sysExternalUnite/v1/save'
    },
    handleClose() {
      this.$emit('update:isShowDialog', false)
      this.cancelConfig()
    },
    handleClick(tab) {},
    handleClickWeek(key) {
      this.currentWeek = key
    },
    handleAddApp() {
      this.currentTitle = '添加应用'
      this.appDetailDialog = true
    },
    handleEdit(row) {
      this.currentTitle = '编辑应用'
    },
    handleDelete(row) {},
    loadData(params,cb){
      cb()
    },
    handleCloseAppDetailDialog(){
      this.appDetailDialog = false
    },
    handleSubmit(){
      this.$root.$validator.validateAll('thirdPartyAppForm').then(result=>{
        if(result){
          const formData =  this.$refs.productAppForm.getFormData()
          console.log(formData)
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.address-form{
  ::v-deep{
    .el-select,.el-date-editor.el-input{
      width: 448px;
    }
  }
}
.week {
  list-style: none;
  display: flex;
  .week-item {
    width: 72px;
    height: 32px;
    line-height: 32px;
    text-align: center;
    color: #666666;
    border: 1px solid #dcdee0;
    border-right: none;
    margin-top: 12px;
    &:hover {
      cursor: pointer;
      color: $--color-primary;
      border: 1px solid $--color-primary;
    }
    &:first-child {
      border-radius: 2px 0px 0px 2px;
    }
    &:last-child {
      border-right: 1px solid #dcdee0;
      border-radius: 0px 2px 2px 0px;
      &:hover {
        border-right-color: $--color-primary;
      }
    }
  }
  .is-active-item {
    color: $--color-primary;
    border: 1px solid $--color-primary;
    &:last-child {
      border-right-color: $--color-primary;
    }
  }
  .hide{
    display: none;
  }
}
</style>
