<template>
  <div class="app-container">
    <el-form ref="form" label-width="110px" :model="formData" :rules="rules">
      <el-form-item label="认证方式:">关联已认证设备</el-form-item>
      <el-form-item label="SN码列表:" prop="snList">
        <el-checkbox-group v-model="formData.snList" />
        <el-button size="mini" type="primary" @click="onChooseCode">选择SN码</el-button>
      </el-form-item>
      <el-form-item>
        <sncode-list class="snCode-list" :selection="false" :control="true" :list="selectedCodeList">
          <template #control="{ row }">
            <el-button size="mini" type="danger" @click="onSelectCodeRemove(row)">删除</el-button>
          </template>
        </sncode-list>
      </el-form-item>
    </el-form>

    <!-- 表单提交 返回 -->
    <div class="control-box">
      <el-button type="primary" @click="submit">保存</el-button>
      <el-button type="warning" @click="navigateBack">返回</el-button>
    </div>

    <!-- 选择sn码 -->
    <el-dialog title="选择关联设备" :visible.sync="dialogCodeListVisible" width="70%" :show-close="false">
      <sncode-list
        :selection="true"
        :control="false"
        :list="unselectedCodeList"
        height="380"
        @selected="onCodeSelected"
      />
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" size="mini" @click="onCodeCancel">取 消</el-button>
        <el-button type="primary" size="mini" @click="onCodeConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { SncodeList } from '@/views/components'
import { fetchClubDeviceSnList, saveProductRelation } from '@/api/product'
import { getStorage } from '@/utils/storage'
import { uniqueArr } from '@/utils'
export default {
  components: {
    SncodeList
  },
  data() {
    return {
      dialogCodeListVisible: false,
      formData: {
        authType: 2,
        authId: '',
        snList: []
      },
      rules: {
        snList: [{ type: 'array', required: true, message: 'SN码列表不能为空', trigger: ['change'] }]
      },
      listQuery: {
        authId: '',
        downStatus: 0,
        productName: '',
        snCode: '',
        authParty: ''
      },
      codeList: [], // sn码列表
      preSelectedCodeList: [] // table中已选中的sn码列表
    }
  },
  computed: {
    // 选中的sn码列表
    selectedCodeList() {
      return this.codeList.filter((item) => this.formData.snList.includes(item.snCode))
    },
    // 剩余未选中的sn码列表
    unselectedCodeList() {
      return this.codeList.filter((item) => !this.formData.snList.includes(item.snCode))
    }
  },
  watch: {
    selectedCodeListAll(nval) {
      this.formData.snList = nval
    }
  },
  created() {
    // 获取当前设备所属机构的id
    this.formData.authId = getStorage('device-setting-authId')
    this.listQuery.authId = this.formData.authId
    this.fetchSnCodeList()
  },
  methods: {
    // 选择sn码
    onChooseCode() {
      this.dialogCodeListVisible = true
    },
    // 获取全部sn码列表
    async fetchSnCodeList() {
      try {
        // 获取全部sn码列表
        this.listQuery.downStatus = 0
        const res1 = await fetchClubDeviceSnList(this.listQuery)
        res1.data = res1.data.map((item) => {
          item.downStatus = 0
          return item
        })
        // 获取与该机构有关联sn码列表
        this.listQuery.downStatus = 1
        const res2 = await fetchClubDeviceSnList(this.listQuery)
        res2.data = res2.data.map((item) => {
          item.downStatus = 0
          return item
        })
        this.codeList = [...res1.data, ...res2.data]
        console.log('🚀 ~ file: bind.vue:108 ~ fetchSnCodeList ~ this.codeList:', this.codeList)
      } catch (error) {
        console.log(error)
      }
    },
    // 保存
    async onSave() {
      try {
        await saveProductRelation(this.formData)
        this.$message.success('关联已认证设备成功')
        this.$store.dispatch('tagsView/delView', this.$route)
        this.$router.push(`/club/device-list?id=${this.formData.authId}`)
      } catch (error) {
        console.log(error)
      }
    },
    // 提交表单
    async submit() {
      try {
        await this.$refs.form.validate()
        this.onSave()
      } catch (error) {
        console.log(error)
      }
    },
    // 选中sn码
    onCodeSelected(list) {
      this.preSelectedCodeList = list
    },
    // 取消选择sn码
    onCodeCancel() {
      this.preSelectedCodeList = []
      this.dialogCodeListVisible = false
    },
    // 确认选择sn码
    onCodeConfirm() {
      const sncodeList = this.preSelectedCodeList.map((item) => item.snCode)
      const snList = [...this.formData.snList, ...sncodeList]
      this.formData.snList = uniqueArr(snList)
      this.dialogCodeListVisible = false
    },
    // 已选中sn码删除
    onSelectCodeRemove(row) {
      this.formData.snList = this.formData.snList.filter((code) => code !== row.snCode)
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  width: 80%;
}
.filter-container {
  background: #eee;
  padding: 6px 10px;

  .filter-control {
    margin-bottom: 0;
  }
}
.snCode-cate {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
}
</style>
