<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="80px">
      <el-form-item label="模板标题" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入模板标题"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option
            v-for="dict in statusOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="备注" prop="remark">
        <el-input
          v-model="queryParams.remark"
          placeholder="请输入备注"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['store:storeProductUserTemp:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['store:storeProductUserTemp:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['store:storeProductUserTemp:remove']"
        >删除</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table border v-loading="loading" :data="FsStoreProductUserTempList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="模板标题" align="center" prop="name" show-overflow-tooltip />
      <el-table-column label="状态" align="center" prop="status" width="100">
        <template slot-scope="scope">
          <dict-tag :options="statusOptions" :value="scope.row.status" />
        </template>
      </el-table-column>
      <el-table-column label="排序" align="center" prop="sort" width="80" />
      <el-table-column label="备注" align="center" prop="remark" show-overflow-tooltip />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="150">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['store:storeProductUserTemp:edit']"
          >修改</el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['store:storeProductUserTemp:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改模板对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="1200px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="模板标题" prop="name">
              <el-input v-model="form.name" placeholder="请输入模板标题" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="排序" prop="sort">
              <el-input-number v-model="form.sort" :min="0" controls-position="right" style="width: 200px;" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="状态" prop="status">
              <el-radio-group v-model="form.status">
                <el-radio
                  v-for="dict in statusOptions"
                  :key="dict.dictValue"
                  :label="parseInt(dict.dictValue)"
                >{{ dict.dictLabel }}</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="form.remark" type="textarea" :rows="2" placeholder="请输入备注" />
        </el-form-item>
        <el-form-item label="选项列表">
          <el-button type="primary" plain icon="el-icon-plus" size="mini" @click="openFieldDialog">新增选项</el-button>
          <el-table
            v-loading="fieldLoading"
            :data="fieldList"
            border
            size="small"
            style="width: 100%; margin-top: 10px;"
            :cell-style="{ textAlign: 'center' }"
            :header-cell-style="{ textAlign: 'center' }"
          >
            <el-table-column label="选项名称" prop="fieldName" min-width="120" show-overflow-tooltip />
            <el-table-column label="是否必填" prop="isRequired" width="90">
              <template slot-scope="scope">
                <el-tag :type="scope.row.isRequired === 1 ? 'danger' : 'info'" size="mini">
                  {{ scope.row.isRequired === 1 ? '是' : '否' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="类型" prop="fieldType" width="90">
              <template slot-scope="scope">
                {{ getFieldTypeLabel(scope.row.fieldType) }}
              </template>
            </el-table-column>
            <el-table-column label="选项内容" prop="fieldOption" min-width="140" show-overflow-tooltip />
            <el-table-column label="排序" prop="sort" width="70" />
            <el-table-column label="状态" prop="status" width="90">
              <template slot-scope="scope">
                <el-tag :type="scope.row.status === 1 ? 'success' : 'info'" size="mini">
                  {{ scope.row.status === 1 ? '启用' : '停用' }}
                </el-tag>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="text"
                  icon="el-icon-delete"
                  @click="deleteFieldRow(scope.row)"
                >删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            v-show="fieldTotal > 0"
            :total="fieldTotal"
            :page.sync="fieldQueryParams.pageNum"
            :limit.sync="fieldQueryParams.pageSize"
            @pagination="handleFieldPagination"
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 新增选项对话框 -->
    <el-dialog title="新增选项" :visible.sync="fieldOpen" width="520px" append-to-body :close-on-click-modal="false">
      <el-form ref="fieldForm" :model="fieldForm" :rules="fieldRules" label-width="90px">
        <el-form-item label="选项名称" prop="fieldName">
          <el-input v-model="fieldForm.fieldName" placeholder="请输入选项名称" />
        </el-form-item>
        <el-form-item label="是否必填" prop="isRequired">
          <el-switch v-model="fieldForm.isRequired" :active-value="1" :inactive-value="0" />
        </el-form-item>
        <el-form-item label="类型" prop="fieldType">
          <el-select v-model="fieldForm.fieldType" placeholder="请选择类型" style="width: 200px;" @change="handleFieldTypeChange">
            <el-option
              v-for="item in fieldTypeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          v-if="fieldForm.fieldType === 'radio' || fieldForm.fieldType === 'checkbox'"
          label="选项内容"
          prop="fieldOption"
        >
          <el-input
            v-model="fieldForm.fieldOption"
            type="textarea"
            :rows="2"
            placeholder="多个选项请用分号分隔，例如：选项A;选项B;选项C"
          />
        </el-form-item>
        <el-form-item label="排序" prop="sort">
          <el-input-number v-model="fieldForm.sort" :min="0" controls-position="right" style="width: 200px;" />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="fieldForm.status">
            <el-radio :label="1">启用</el-radio>
            <el-radio :label="0">停用</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="fieldSubmitLoading" @click="submitFieldForm">确 定</el-button>
        <el-button @click="fieldOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listFsStoreProductUserTemp,
  getFsStoreProductUserTemp,
  delFsStoreProductUserTemp,
  addFsStoreProductUserTemp,
  updateFsStoreProductUserTemp
} from '@/api/hisStore/storeProductUserTemp'
import {
  listFsStoreProductUserTempField,
  addFsStoreProductUserTempField,
  delFsStoreProductUserTempField
} from '@/api/hisStore/storeProductUserTempField'

export default {
  name: 'FsStoreProductUserTemp',
  data() {
    const validateFieldOption = (rule, value, callback) => {
      const type = this.fieldForm.fieldType
      if ((type === 'radio' || type === 'checkbox') && !value) {
        callback(new Error('请填写选项内容，多个选项用分号分隔'))
      } else {
        callback()
      }
    }
    return {
      loading: true,
      ids: [],
      single: true,
      multiple: true,
      showSearch: true,
      total: 0,
      FsStoreProductUserTempList: [],
      title: '',
      open: false,
      fieldOpen: false,
      fieldSubmitLoading: false,
      fieldLoading: false,
      fieldList: [],
      fieldTotal: 0,
      fieldQueryParams: {
        pageNum: 1,
        pageSize: 10,
        tempId: null
      },
      statusOptions: [],
      fieldTypeOptions: [
        { label: '文本', value: 'text' },
        { label: '单选', value: 'radio' },
        { label: '复选', value: 'checkbox' }
      ],
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        sort: null,
        status: null,
        remark: null
      },
      form: {},
      fieldForm: {},
      rules: {
        name: [{ required: true, message: '模板标题不能为空', trigger: 'blur' }],
        sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }]
      },
      fieldRules: {
        fieldName: [{ required: true, message: '选项名称不能为空', trigger: 'blur' }],
        fieldType: [{ required: true, message: '请选择类型', trigger: 'change' }],
        sort: [{ required: true, message: '排序不能为空', trigger: 'blur' }],
        fieldOption: [{ validator: validateFieldOption, trigger: 'blur' }]
      }
    }
  },
  created() {
    this.getList()
    this.getDicts('sys_company_status').then(response => {
      this.statusOptions = response.data
    })
  },
  methods: {
    parseTemplateId(response) {
      if (response.id != null && response.id !== '') {
        return response.id
      }
      const data = response.data
      if (data == null || data === '') {
        return null
      }
      if (typeof data === 'object') {
        return data.id != null && data.id !== '' ? data.id : null
      }
      return data
    },
    fetchTemplateIdByName() {
      return listFsStoreProductUserTemp({
        name: this.form.name,
        pageNum: 1,
        pageSize: 10
      }).then(response => {
        const rows = (response.rows || []).filter(item => item.name === this.form.name)
        if (!rows.length) {
          return null
        }
        rows.sort((a, b) => Number(b.id) - Number(a.id))
        return rows[0].id
      })
    },
    resolveTemplateIdFromResponse(response) {
      const id = this.parseTemplateId(response)
      if (id != null) {
        return Promise.resolve(id)
      }
      return this.fetchTemplateIdByName()
    },
    saveTemplateAndGetId() {
      return addFsStoreProductUserTemp(this.buildTemplatePayload()).then(response => {
        if (response.code !== 200) {
          return Promise.reject()
        }
        return this.resolveTemplateIdFromResponse(response)
      })
    },
    buildTemplatePayload() {
      const payload = { ...this.form }
      if (payload.id == null || payload.id === '') {
        delete payload.id
      }
      return payload
    },
    hasTemplateId() {
      return this.form.id != null && this.form.id !== ''
    },
    mapFieldItem(item) {
      return {
        id: item.id,
        tempId: item.tempId,
        fieldName: item.fieldName,
        isRequired: item.isRequired != null ? Number(item.isRequired) : 0,
        fieldType: item.fieldType,
        fieldOption: item.fieldOption || '',
        sort: item.sort != null ? Number(item.sort) : 0,
        status: item.status != null ? Number(item.status) : 1
      }
    },
    getFieldTypeLabel(value) {
      const item = this.fieldTypeOptions.find(opt => opt.value === value)
      return item ? item.label : value
    },
    getList() {
      this.loading = true
      listFsStoreProductUserTemp(this.queryParams).then(response => {
        this.FsStoreProductUserTempList = response.rows
        this.total = response.total
        this.loading = false
      })
    },
    loadFieldList(tempId, resetPage = true) {
      if (tempId != null && tempId !== '') {
        this.fieldQueryParams.tempId = tempId
        if (resetPage) {
          this.fieldQueryParams.pageNum = 1
        }
      }
      if (!this.fieldQueryParams.tempId) {
        this.fieldList = []
        this.fieldTotal = 0
        return Promise.resolve()
      }
      this.fieldLoading = true
      return listFsStoreProductUserTempField({
        tempId: this.fieldQueryParams.tempId,
        pageNum: this.fieldQueryParams.pageNum,
        pageSize: this.fieldQueryParams.pageSize
      }).then(response => {
        this.fieldList = (response.rows || []).map(item => this.mapFieldItem(item))
        this.fieldTotal = response.total || 0
      }).finally(() => {
        this.fieldLoading = false
      })
    },
    handleFieldPagination() {
      this.loadFieldList(null, false)
    },
    cancel() {
      this.open = false
      this.reset()
    },
    reset() {
      this.form = {
        id: null,
        name: null,
        sort: 0,
        status: 1,
        remark: null
      }
      this.fieldList = []
      this.fieldTotal = 0
      this.fieldQueryParams = {
        pageNum: 1,
        pageSize: 10,
        tempId: null
      }
      this.resetForm('form')
    },
    resetFieldForm() {
      this.fieldForm = {
        fieldName: null,
        isRequired: 0,
        fieldType: 'text',
        fieldOption: '',
        sort: 0,
        status: 1
      }
      this.resetForm('fieldForm')
    },
    handleQuery() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    resetQuery() {
      this.resetForm('queryForm')
      this.handleQuery()
    },
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    handleAdd() {
      this.reset()
      this.open = true
      this.title = '添加商品信息采集模板'
    },
    handleUpdate(row) {
      this.reset()
      const id = row.id || this.ids
      getFsStoreProductUserTemp(id).then(response => {
        this.form = response.data
        this.form.status = this.form.status != null ? Number(this.form.status) : 1
        this.form.sort = this.form.sort != null ? Number(this.form.sort) : 0
        return this.loadFieldList(id)
      }).then(() => {
        this.open = true
        this.title = '修改商品信息采集模板'
      })
    },
    openFieldDialog() {
      this.resetFieldForm()
      this.fieldOpen = true
    },
    handleFieldTypeChange() {
      if (this.fieldForm.fieldType === 'text') {
        this.fieldForm.fieldOption = ''
      }
    },
    addTemplateIfNeeded() {
      if (this.hasTemplateId()) {
        return Promise.resolve(this.form.id)
      }
      return new Promise((resolve, reject) => {
        this.$refs.form.validate(valid => {
          if (!valid) {
            this.$message.warning('请先完善模板基本信息')
            reject()
            return
          }
          this.saveTemplateAndGetId().then(id => {
            if (id == null) {
              this.$message.error('模板已保存，但未获取到模板编号，无法新增选项')
              reject()
              return
            }
            this.$set(this.form, 'id', id)
            this.title = '修改商品信息采集模板'
            resolve(id)
          }).catch(() => {
            this.$message.error('模板保存失败，无法新增选项')
            reject()
          })
        })
      })
    },
    submitFieldForm() {
      this.$refs.fieldForm.validate(valid => {
        if (!valid) {
          return
        }
        this.fieldSubmitLoading = true
        this.addTemplateIfNeeded()
          .then(templateId => {
            return addFsStoreProductUserTempField({
              ...this.fieldForm,
              tempId: templateId
            })
          })
          .then(response => {
            if (response.code === 200) {
              this.msgSuccess('新增选项成功')
              this.fieldOpen = false
              return this.loadFieldList(this.form.id)
            }
            this.$message.error('新增选项失败')
          })
          .catch(() => {})
          .finally(() => {
            this.fieldSubmitLoading = false
          })
      })
    },
    deleteFieldRow(row) {
      if (row && row.id) {
        this.$confirm('是否确认删除该选项?', '警告', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          return delFsStoreProductUserTempField(row.id)
        }).then(() => {
          this.msgSuccess('删除成功')
          if (this.fieldList.length === 1 && this.fieldQueryParams.pageNum > 1) {
            this.fieldQueryParams.pageNum -= 1
          }
          return this.loadFieldList(null, false)
        }).catch(() => {})
      }
    },
    submitForm() {
      this.$refs.form.validate(valid => {
        if (!valid) {
          return
        }
        const isUpdate = this.hasTemplateId()
        const request = isUpdate
          ? updateFsStoreProductUserTemp({ ...this.form })
          : addFsStoreProductUserTemp(this.buildTemplatePayload())
        request.then(response => {
          if (response.code === 200) {
            if (!isUpdate) {
              this.resolveTemplateIdFromResponse(response).then(id => {
                if (id != null) {
                  this.$set(this.form, 'id', id)
                }
              })
            }
            this.msgSuccess(isUpdate ? '修改成功' : '新增成功')
            this.open = false
            this.getList()
          }
        })
      })
    },
    handleDelete(row) {
      const ids = row.id || this.ids
      this.$confirm('是否确认删除商品信息采集模板编号为"' + ids + '"的数据项?', '警告', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        return delFsStoreProductUserTemp(ids)
      }).then(() => {
        this.getList()
        this.msgSuccess('删除成功')
      }).catch(() => {})
    }
  }
}
</script>
