<template>
  <view class="p-20rpx h-full overflow-hidden flex flex-col">
    <view class="flex-1 relative">
      <view class="absolute top-0 left-0 w-full h-full">
        <scroll-view scroll-y="true" class="h-full">
          <u-form ref="uForm" :model="form" class="cu-form" label-width="200">
            <u-form-item label="ID" v-if="form.id">
              <u-input disabled v-model="form.id"></u-input>
            </u-form-item>
            <u-form-item label="产业">
              <ApiSelect
                v-model="form.category_id"
                v-bind="categorySelectOption"
              ></ApiSelect>
            </u-form-item>
            <u-form-item label="名称">
              <u-input v-model="form.name"></u-input>
            </u-form-item>
            <u-form-item label="上级">
              <ApiSelect
                v-model="form.parent_id"
                v-bind="parentSelectOption"
                @options-change="handleParentChange"
              ></ApiSelect>
            </u-form-item>
            <u-form-item label="单位">
              <u-input v-model="form.unit"></u-input>
            </u-form-item>
            <u-form-item label="是否是结点">
              <u-switch v-model="form.is_end"></u-switch>
            </u-form-item>
            <u-form-item v-if="form.is_end" label="">
              <view>
                <view
                  class="w-full flex my-10rpx"
                  v-for="(arr, j) in form.extends"
                  :key="j"
                >
                  <view class="flex-1 mr-20rpx">
                    <u-input
                      :clearable="false"
                      border
                      v-model="arr.name"
                      placeholder="请输入名称"
                    />
                  </view>
                  <view class="flex-1 flex items-center">
                    <u-input
                      :clearable="false"
                      border
                      v-model="arr.unit"
                      placeholder="请输入单位"
                    />
                  </view>
                  <view v-if="j == 0" class="px-10rpx">
                    <u-icon @click="addDomain()" name="plus" size="34"></u-icon>
                  </view>
                  <view class="px-10rpx" v-else>
                    <u-icon
                      @click="removeDomain(j)"
                      name="minus"
                      size="34"
                    ></u-icon>
                  </view>
                </view>
              </view>
            </u-form-item>
          </u-form>
        </scroll-view>
      </view>
    </view>
    <view class="grid grid-cols-2 gap-x-20rpx">
      <u-button class="mt-20rpx" round @click="handleCancel"> 取消 </u-button>
      <u-button class="mt-20rpx" type="primary" round @click="handleSubmit">
        保存
      </u-button>
    </view>
  </view>
</template>
<script>
import { http } from '@/api/index.js'
import ApiSelect from '@/components/search-form/components/ApiSelect1.vue'
import ApiCheckbox from '@/components/search-form/components/ApiCheckbox.vue'
const categorySelectOption = {
  api: async (e) => {
    const { data } = await http.get('/api/keywords-crops-cate', {
      params: e,
    })
    return data.data
  },
  labelField: 'name',
  valueField: 'id',
}
const parentSelectOption = {
  api: async (e) => {
    const { data } = await http.get('/api/crops', {
      params: e,
    })
    return data.data.filter(({ is_end }) => is_end != 1)
  },
  labelField: 'name',
  valueField: 'id',
}

export default {
  props: {
    data: {
      type: Object,
      default: () => {},
    },
    crop_type: {
      type: Number,
      default: 2,
    },
  },
  components: {
    ApiSelect,
    ApiCheckbox,
  },
  computed: {
    isEdit() {
      return !!this.data
    },
    parentSelectOption() {
      return {
        ...parentSelectOption,
        params: {
          type: 'all',
          crop_type: this.crop_type,
          category: this.form.category_id,
        },
      }
    },
  },
  data() {
    return {
      categorySelectOption,

      form: {
        id: '',
        category_id: '',
        name: '',
        parent_id: '',
        unit: '',
        is_end: false,
        extends: [
          {
            name: '',
            unit: '',
          },
        ],
      },
    }
  },
  methods: {
    addDomain() {
      this.form.extends.push({
        name: '',
        unit: '',
      })
    },
    removeDomain(index) {
      this.form.extends.splice(index, 1)
    },
    handleParentChange(e) {
      // this.form.parent_id = ''
    },
    handleCancel() {
      this.$emit('cancel')
    },
    async handleSubmit() {
      const params = { ...this.form, crop_type: this.crop_type }
      if (this.isEdit) {
        await this.onUpdate(params)
      } else {
        await this.onCreate(params)
      }
      this.$emit('confirm')
    },

    async onUpdate(params) {
      try {
        await this.$http.put(`/api/crops/${params.id}`, params)
        this.$u.toast('操作成功')
      } catch ({ data }) {
        data && this.$u.toast(data?.message)
      }
    },

    async onCreate(params) {
      try {
        await this.$http.post('/api/crops', params)
        this.$u.toast('操作成功')
      } catch ({ data }) {
        data && this.$u.toast(data?.message)
      }
    },

    async setDefaultForm(e) {
      const { data } = await this.$http.get(`/api/crops/${e.id}`)
      const { data: resData } = data

      Object.keys(e).forEach((key) => {
        let value = e[key]
        if (key == 'is_end') value = value == 1
        if (key == 'extends') {
          if (value.length == 0) value = [{ name: '', unit: '' }]
        }
        if (this.form[key] !== undefined) this.form[key] = value
      })

      this.form.category_id = resData?.category?.id
      this.form.parent_id = resData?.parent_id > 0 ? resData?.parent_id : null
    },
  },
  watch: {
    data: {
      handler(val) {
        console.log(val)
        if (val) {
          this.setDefaultForm(val)
        }
      },
      immediate: true,
      deep: true,
    },
  },
}
</script>
