<template>
  <el-table
    border
    :data="tableData"
    style="">
    <el-table-column
      width="250px"
      label="始发地">
      <template v-slot="{ row, column, $index }">
        <el-checkbox v-model="row.checked" @change="updateValue(true)">{{ warehouseList[$index].titleZh }}</el-checkbox>
      </template>
    </el-table-column>
    <el-table-column
      prop="objectiveId"
      label="目的地">
      <template v-slot="{ row, column, $index }">
        <el-select v-model="tableData[$index].objectiveIds" multiple placeholder="请选择" style="width:100%" @change="updateValue(row.checked)">
          <el-option
            v-for="item in importCityList"
            :key="item.id"
            :label="item.titleZh"
            :value="item.id">
          </el-option>
        </el-select>
      </template>
    </el-table-column>
  </el-table>
</template>

<script>
export default {
  name: 'CustomerLineTable',
  props: {
    warehouseList: Array,
    importCityList: Array,
    value: Array,
    zhongPaoType: {
      type: Number,
      default: 0
    }
  },
  data() {
    return {
      tableData: []
    }
  },
  mounted() {
    this.freshTableData()
  },
  methods: {
    /**
     * 解析 value
     */
    freshTableData(){
      const foo = []
      let index = 0
      this.warehouseList.forEach(e => {
        let bar = this.tableData.length > 0 ? this.tableData[index] : {
          departureId: e.id,
          objectiveIds: [],
          checked: false
        }
        const valueIndex = this.value.findIndex(v => v.departureId === e.id)
        if(valueIndex !== -1) {
          bar = { ...this.value[valueIndex], checked: true }

          if(bar.objectiveIds.length === 0) {
            bar.objectiveIds = []
          } else {
            bar.objectiveIds = bar.objectiveIds.split(',').map(m => parseInt(m))
          }
        }
        foo.push(bar)
        index++
      })
      this.tableData = foo
    },
    /**
     * 更新 value
     */
    updateValue(really = true){
      if (!really) return
      const result = []
      this.tableData.forEach(e => {
        if(e.checked){
          const { departureId } = e
          let objectiveIds = e.objectiveIds.join(',')
          result.push({ departureId, objectiveIds, zhongPaoType: this.zhongPaoType })
        }
      })
      this.$emit('input', result)
    }
  },
  watch: {
    value() {
      this.freshTableData()
    },
    warehouseList() {
      this.freshTableData()
    }
  }
}
</script>

<style scoped>

</style>
