<!--商家端-代客下单-->
<template>
  <el-dialog
    append-to-body
    custom-class="center-dialog"
    heiht="90%"
    :title="title"
    top="0vh"
    :visible.sync="dialogFormVisible"
    width="70%"
    @close="close"
  >
    <el-scrollbar style="height: 600px">
      <el-form
        ref="form"
        v-loading="listLoading"
        label-width="40px"
        :model="form"
        :rules="rules"
      >
        <el-form-item>
          <el-button
            class="el-icon-circle-plus-outline"
            type="info"
            @click="showItemTable"
          >
            {{ __('添加行') }}
          </el-button>
        </el-form-item>
        <el-form-item>
          <el-table
            border
            :data="items"
            height="500"
            width="60%"
            @cell-click="tabClick"
          >
            <el-table-column
              align="center"
              :label="__('操作')"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <el-button type="text" @click="deleteRow(scope.$index)">
                  {{ __('删除') }}
                </el-button>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              :label="__('商品SKU')"
              prop="item_id"
              show-overflow-tooltip
            />
            <el-table-column
              align="center"
              :label="__('商品名称')"
              prop="item_name"
              show-overflow-tooltip
            />
            <el-table-column
              align="center"
              :label="__('数量')"
              prop="cart_quantity"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <span
                  v-if="
                    scope.row.item_id === tabClickIndex &&
                    scope.column.id === columnId
                  "
                >
                  <el-input
                    ref="editInput"
                    v-model="scope.row.cart_quantity"
                    @blur.stop="inputBlur"
                  />
                </span>
                <span v-else>{{ scope.row.cart_quantity }}</span>
              </template>
            </el-table-column>
            <el-table-column
              align="center"
              :label="__('单价')"
              prop="item_unit_price"
              show-overflow-tooltip
            >
              <template slot-scope="scope">
                <span
                  v-if="
                    scope.row.item_id === tabClickIndex &&
                    scope.column.id === columnId
                  "
                >
                  <el-input
                    ref="editInput"
                    v-model="scope.row.item_unit_price"
                    @blur.stop="inputBlur"
                  />
                </span>
                <span v-else>{{ scope.row.item_unit_price }}</span>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>
        <el-form-item prop="buyer_user_id">
          <el-select
            v-model="form.buyer_user_id"
            clearable
            filterable
            :loading="loading"
            :placeholder="__('请输入买家用户名称')"
            remote
            :remote-method="remoteFindUserList"
            reserve-keyword
            @change="change"
          >
            <el-option
              v-for="item in userList"
              :key="item.user_id"
              :label="item.user_account"
              :value="item.user_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item prop="ud_id">
          <el-select
            v-model="form.ud_id"
            clearable
            :placeholder="__('请选择收货地址')"
          >
            <el-option
              v-for="item in addressList"
              :key="item.ud_id"
              :label="item.ud_address"
              :value="item.ud_id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button
            class="el-icon-circle-plus-outline"
            type="info"
            @click="showAddressEdit"
          >
            {{ __('添加新地址') }}
          </el-button>
        </el-form-item>
      </el-form>
    </el-scrollbar>
    <ProductItemTable ref="productItemTable" @checkItem="getCheckItem" />
    <AddressEdit ref="addressEdit" @fetch-data="getAdderssList" />
    <div slot="footer" class="dialog-footer">
      <el-button @click="close">{{ __('取消') }}</el-button>
      <el-button type="primary" @click="save">{{ __('确定') }}</el-button>
    </div>
  </el-dialog>
</template>
<script>
  import { translateTitle as __ } from '@/utils/i18n'
  import { getList } from '@/api/user/base'
  import { getList as getAdderssList } from '@/api/user/delivery/address'
  import ProductItemTable from '@/components/activity/ProductItemDialogTable'
  import AddressEdit from './AddressEdit'
  import { add } from '@/api/order/base'

  export default {
    name: 'OrderBaseEdit',
    components: { ProductItemTable, AddressEdit },
    data() {
      return {
        tabClickIndex: null, // 点击的行
        columnId: null, // 点击的列
        addressList: [],
        form: {},
        userList: [],
        items: [],
        listLoading: false,
        dialogFormVisible: false,
        title: '',
        loading: false,
        rules: {
          buyer_user_id: [
            {
              required: true,
              message: '请选择客户',
              trigger: 'change',
            },
          ],
          // ud_id: [
          //   {
          //     required: true,
          //     message: '请选择地址',
          //     trigger: 'change',
          //   },
          // ],
        },
      }
    },
    methods: {
      __,
      change(user_id) {
        if (user_id) {
          this.getAdderssList(user_id)
        } else {
          this.addressList = []
        }
      },
      async getAdderssList(user_id) {
        if (!user_id) {
          user_id = this.form.buyer_user_id
        }

        if (user_id) {
          const { data } = await getAdderssList({
            user_id: user_id,
            pageNum: 1,
            pageSize: 200,
          })
          this.addressList = data.items
        }
      },
      // 查询用户信息列表
      async remoteFindUserList(user_nickname) {
        if (user_nickname !== '') {
          this.loading = true;
          setTimeout(() => {
            this.loading = false
            getList({ user_nickname: user_nickname }).then((res) => {
              this.userList = res.data.items
            })
          }, 200)
        } else {
          this.userList = []
        }
      },
      showEdit() {
        this.dialogFormVisible = true
      },
      close() {
        this.form = {}
        this.items = []
        this.$refs['form'].resetFields()
        this.dialogFormVisible = false
      },
      async save() {
        if (this.items.length === 0) {
          this.$baseMessage('请先添加商品', 'success')
          return
        }
        this.$refs['form'].validate(async (valid) => {
          if (valid) {
            this.listLoading = true
            const { msg, status } = await add(this.getParam())
            if (200 == status) {
              this.$baseMessage(msg, 'success')
            } else {
              this.$baseMessage(msg, 'error')
            }
            this.$emit('fetch-data')
            this.close()
            this.listLoading = false
          } else {
            this.listLoading = false
            return false
          }
        })
      },
      getParam() {
        let obj = {
          user_id: this.form.buyer_user_id,
          ud_id: this.form.ud_id,
          items: JSON.stringify(this.items),
        }
        return obj
      },
      showItemTable() {
        this.$refs['productItemTable'].showTable()
      },
      getCheckItem(row) {
        let obj = {
          item_id: row.item_id,
          item_name: row.item_name,
          item_unit_price: row.item_unit_price,
          cart_quantity: 1,
          kind_id: row.kind_id,
        }
        this.items.push(obj)
      },
      deleteRow(index) {
        this.$baseConfirm(this.__('你确定要删除当前项吗'), null, async () => {
          this.items.splice(index, 1)
        })
      },
      showAddressEdit() {
        if (this.form.buyer_user_id) {
          this.$refs['addressEdit'].showEdit(this.form.buyer_user_id)
        } else {
          this.$baseMessage('请先选择客户', 'success')
        }
      },
      tabClick(row, column) {
        this.tabClickIndex = row.item_id
        this.columnId = column.id
        // inout 获取焦点
        this.$nextTick(() => {
          if (!this.$refs['editInput']) return
          this.$refs['editInput'].focus()
        })
      },
      // 失去焦点初始化
      async inputBlur() {
        this.tabClickIndex = null
        this.columnId = null
      },
    },
  }
</script>
