<template>
  <div class="page-form-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="sncodeType">
        <el-radio-group v-model="formData.sncodeType" size="mini">
          <el-radio :label="1">所有设备SN码</el-radio>
          <el-radio :label="2">关联机构设备SN码</el-radio>
        </el-radio-group>
      </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="filterSelectedCodeList"
          @filter="onSelectCodeFilter"
        >
          <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="dialogTextTip" :visible.sync="dialogCodeListVisible" width="30%" :show-close="false">
      <sncode-list
        v-if="dialogCodeListVisible"
        :selection="true"
        :control="false"
        :list="filterCodeList"
        height="280"
        @filter="onCodeFilter"
        @selected="onCodeChange"
      />
      <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 { fetchProductSnList, fetchProductSnListType, saveProductRelation } from '@/api/product'
import { getStorage } from '@/utils/storage'
export default {
  components: {
    SncodeList
  },
  data() {
    return {
      dialogCodeListVisible: false,
      formData: {
        authType: 2,
        authId: '',
        sncodeType: 1,
        snList: []
      },
      rules: {
        snList: [{ type: 'array', required: true, message: 'SN码列表不能为空', trigger: ['change'] }]
      },
      listQuery: {
        sncode: ''
      },
      codeList: [],
      filterCodeList: [],
      selectedCodeList: [],
      selectedCodeListAll: [],
      filterSelectedCodeList: []
    }
  },
  computed: {
    dialogTextTip() {
      return this.formData.sncodeType === 1 ? '所有设备SN码' : '关联机构设备SN码'
    }
  },
  watch: {
    selectedCodeListAll(nval) {
      this.formData.snList = nval
    }
  },
  created() {
    // 获取当前设备所属机构的id
    this.formData.authId = getStorage('device-setting-authId')
  },
  methods: {
    // 选择sn码
    onChooseCode() {
      this.dialogCodeListVisible = true
      if (this.formData.sncodeType === 1) {
        this.fetchSnCodeListAll()
      } else {
        this.fetchSnCodeListSelf()
      }
    },
    // 获取全部sn码列表
    async fetchSnCodeListSelf() {
      try {
        const res = await fetchProductSnListType({ authId: this.formData.authId })
        if (!res.data) return
        this.codeList = res.data.filter((code) => !this.selectedCodeListAll.includes(code))
        this.filterCodeList = this.codeList
        console.log(res)
      } catch (error) {
        console.log(error)
      }
    },
    // 获取关联机构sn码列表
    async fetchSnCodeListAll() {
      try {
        const res = await fetchProductSnList({ authId: this.formData.authId })
        if (!res.data) return
        this.codeList = res.data.filter((code) => !this.selectedCodeListAll.includes(code))
        this.filterCodeList = this.codeList
        console.log(res)
      } 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码列表
    onCodeFilter(query) {
      this.filterCodeList = this.codeList.filter((code) => new RegExp(query.sncode, 'gi').test(code))
    },
    // 选中sn码
    onCodeChange(value) {
      this.selectedCodeList = value
    },
    // 取消选择sn码
    onCodeCancel() {
      this.selectedCodeListAll = [...this.selectedCodeListAll, ...this.selectedCodeList]
      this.selectedCodeList = []
      this.filterCodeList = []
      this.dialogCodeListVisible = false
    },
    // 确认选择sn码
    onCodeConfirm() {
      this.selectedCodeListAll = [...this.selectedCodeListAll, ...this.selectedCodeList]
      this.filterSelectedCodeList = this.selectedCodeListAll
      this.filterCodeList = []
      this.dialogCodeListVisible = false
    },
    // 已选中sn码筛选
    onSelectCodeFilter(query) {
      this.filterSelectedCodeList = this.filterSelectedCodeList.filter((code) =>
        new RegExp(query.sncode, 'gi').test(code)
      )
    },
    // 已选中sn码删除
    onSelectCodeRemove(row) {
      this.selectedCodeListAll = this.selectedCodeListAll.filter((code) => code !== row)
      this.filterSelectedCodeList = this.selectedCodeListAll
    }
  }
}
</script>

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

  .filter-control {
    margin-bottom: 0;
  }
}
</style>
