<template>
  <div>
    <el-form :inline="true" label-position="top" style="margin-top: 10px">
      <el-form-item >
        <el-button type="primary" @click="openUserPicker">选择账号</el-button>
        <el-button type="primary" :loading="saving" @click="save">保存</el-button>
      </el-form-item>
    </el-form>
    <div class="rq">
      <el-table :data="rows" border style="width: 100%" height="400">
        <el-table-column prop="userName" label="账号" min-width="180" />
        <el-table-column label="启用" width="100" align="center">
          <template slot-scope="{ row }">
            <el-select v-model="row.active" size="mini" style="width: 80px">
              <el-option label="Y" value="Y" />
              <el-option label="N" value="N" />
            </el-select>
          </template>
        </el-table-column>
        <el-table-column label="备注" min-width="220">
          <template slot-scope="{ row }">
            <el-input v-model="row.remark" size="mini" />
          </template>
        </el-table-column>
        <el-table-column label="操作" width="80" align="center">
          <template slot-scope="scope">
            <el-link type="danger" @click="removeRow(scope.$index)">删除</el-link>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <el-dialog
      title="选择账号"
      :visible.sync="pickerVisible"
      width="900px"
      top="6vh"
      append-to-body
      :close-on-click-modal="false">
      <el-form :inline="true" label-position="top">
        <el-form-item label="账号">
          <el-input v-model="pickerQuery.username" clearable placeholder="请输入账号" style="width: 180px" />
        </el-form-item>
        <el-form-item label="名称">
          <el-input v-model="pickerQuery.userDisplay" clearable placeholder="请输入名称" style="width: 180px" />
        </el-form-item>
        <el-form-item label=" ">
          <el-button type="primary" @click="fetchPickerRows">查询</el-button>
          <el-button @click="resetPickerQuery">重置</el-button>
        </el-form-item>
      </el-form>
      <el-table
        ref="pickerTable"
        :data="pickerRows"
        border
        height="420"
        v-loading="pickerLoading"
        @selection-change="onPickerSelectionChange">
        <el-table-column type="selection" width="55" />
        <el-table-column prop="username" label="账号" min-width="180" />
        <el-table-column prop="userDisplay" label="名称" min-width="180" />
      </el-table>
      <div slot="footer" class="dialog-footer">
        <el-button @click="pickerVisible = false">取消</el-button>
        <el-button type="primary" @click="confirmPickUsers">确认添加</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listPoCustomerUserScope,
  savePoCustomerUserScope,
  searchSiteUserList
} from '@/api/order/poCustomer'

export default {
  name: 'ComPoCustomerUserScope',
  props: {
    site: { type: String, required: true },
    customerCode: { type: String, default: '' }
  },
  data () {
    return {
      rows: [],
      saving: false,
      pickerVisible: false,
      pickerLoading: false,
      pickerRows: [],
      pickerSelection: [],
      pickerQuery: {
        username: '',
        userDisplay: ''
      }
    }
  },
  watch: {
    customerCode: {
      immediate: true,
      handler () { this.load() }
    }
  },
  methods: {
    load () {
      if (!this.customerCode) {
        this.rows = []
        return
      }
      listPoCustomerUserScope({ site: this.site, customerCode: this.customerCode }).then(({ data }) => {
        const rows = (data && data.code === 0 && data.rows) ? data.rows : []
        this.rows = rows.map(this.normalizeScopeRow)
      }).catch(() => {
        this.rows = []
      })
    },
    normalizeScopeRow (row) {
      return {
        userName: (row && row.userName ? String(row.userName).trim() : ''),
        active: row && row.active === 'N' ? 'N' : 'Y',
        remark: row && row.remark ? String(row.remark) : ''
      }
    },
    openUserPicker () {
      if (!this.customerCode) {
        this.$message.warning('请先选择Customer')
        return
      }
      this.pickerVisible = true
      this.pickerSelection = []
      this.fetchPickerRows()
    },
    resetPickerQuery () {
      this.pickerQuery = { username: '', userDisplay: '' }
      this.fetchPickerRows()
    },
    fetchPickerRows () {
      this.pickerLoading = true
      searchSiteUserList({
        site: this.site,
        username: this.pickerQuery.username || '',
        userDisplay: this.pickerQuery.userDisplay || ''
      }).then(({ data }) => {
        if (data && data.code === 0) {
          this.pickerRows = data.rows || []
          this.$nextTick(() => {
            if (this.$refs.pickerTable) {
              this.$refs.pickerTable.clearSelection()
            }
          })
        } else {
          this.pickerRows = []
          this.$message.error((data && data.msg) || '加载账号清单失败')
        }
      }).catch(() => {
        this.pickerRows = []
        this.$message.error('加载账号清单失败')
      }).finally(() => {
        this.pickerLoading = false
      })
    },
    onPickerSelectionChange (selection) {
      this.pickerSelection = selection || []
    },
    confirmPickUsers () {
      if (!this.pickerSelection.length) {
        this.$message.warning('请至少选择一个账号')
        return
      }
      const exists = new Set(this.rows.map(r => (r.userName || '').toLowerCase()))
      let added = 0
      let ignored = 0
      this.pickerSelection.forEach(user => {
        const userName = user && user.username ? String(user.username).trim() : ''
        if (!userName) {
          return
        }
        const key = userName.toLowerCase()
        if (exists.has(key)) {
          ignored++
          return
        }
        this.rows.push({
          userName,
          active: 'Y',
          remark: ''
        })
        exists.add(key)
        added++
      })
      this.pickerVisible = false
      if (added > 0 && ignored > 0) {
        this.$message.success(`已添加 ${added} 个账号，忽略 ${ignored} 个已存在账号`)
      } else if (added > 0) {
        this.$message.success(`已添加 ${added} 个账号`)
      } else {
        this.$message.warning('所选账号均已存在，未新增')
      }
    },
    removeRow (index) {
      this.rows.splice(index, 1)
    },
    save () {
      if (!this.customerCode) return
      const dedupMap = new Map()
      this.rows.forEach(row => {
        const userName = row && row.userName ? String(row.userName).trim() : ''
        if (!userName) {
          return
        }
        const key = userName.toLowerCase()
        if (dedupMap.has(key)) {
          return
        }
        dedupMap.set(key, {
          userName,
          active: row.active === 'N' ? 'N' : 'Y',
          remark: row.remark ? String(row.remark) : ''
        })
      })
      const payloadRows = Array.from(dedupMap.values())
      this.saving = true
      savePoCustomerUserScope({
        site: this.site,
        customerCode: this.customerCode,
        rows: payloadRows
      }).then(({ data }) => {
        this.saving = false
        if (data && data.code === 0) {
          this.$message.success('保存成功')
          this.load()
        } else {
          this.$message.error((data && data.msg) || '保存失败')
        }
      }).catch(() => {
        this.saving = false
        this.$message.error('保存失败')
      })
    }
  }
}
</script>
