<template>
  <zj-tab-page ref="tabPage" :defaultActives="[{ key: 'list', label: $route.meta.title + '-列表', essential: true }]">
    <template slot-scope="{ activeKey, data }">
      <template-page
        v-if="activeKey == 'list'"
        ref="pageRef"
        :get-list="getList"
        :table-attributes="tableAttributes"
        :table-events="tableEvents"
        :options-evens-group="optionsEvensGroup"
        :moreParameters="moreParameters"
        :column-parsing="columnParsing"
        :operation="operation()"
        :exportList="exportList"
        :operationColumnWidth="80"
      >
        <div slot="moreSearch">
          <el-radio-group v-model="status" size="mini" @change="changeType">
            <el-radio-button label="">全部</el-radio-button>
            <el-radio-button :label="false">已关闭</el-radio-button>
            <el-radio-button :label="true">已开启</el-radio-button>
          </el-radio-group>
          <br /><br />
        </div>
      </template-page>
      <div v-if="~['add', 'edit', 'detail'].indexOf(activeKey)">
        <div class="page">
          <el-steps :active="stepIndex" align-center>
            <el-step title="编辑基础信息" description=""></el-step>
            <el-step title="编辑价格库存" description=""></el-step>
            <el-step title="编辑商品详情" description=""></el-step>
          </el-steps>
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>{{
                stepIndex == 0 ? '基础信息' : stepIndex == 1 ? '价格库存' : stepIndex == 2 ? '详情内容' : ''
              }}</span>
            </div>
            <div class="mymain-container">
              <el-form
                ref="formRef"
                :rules="rules"
                :model="formData"
                label-width="110px"
                size="small"
                label-position="left"
              >
                <el-row :gutter="20" justify="start">
                  <div v-show="stepIndex == 0">
                    <el-col :span="24">
                      <el-form-item label="商品可选状态" prop="status" :required="true">
                        <div class="flex_ac">
                          <el-radio-group v-model="formData.status">
                            <el-radio :label="true">开启</el-radio>
                            <el-radio :label="false">关闭</el-radio>
                          </el-radio-group>
                          <div class="hui" style="margin-left: 80px">
                            开启状态，商户可选择本商品；关闭则不允许商户选择；
                          </div>
                        </div>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item
                        label="品牌"
                        prop="brandName"
                        :rules="[{ required: true, message: `请输入品牌`, trigger: 'blur' }]"
                      >
                        <el-input type="text" v-model="formData.brandName" placeholder="请输入"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item label="是否虚拟商品" prop="isVr" :required="true">
                        <el-radio-group v-model="formData.isVr">
                          <el-radio :label="true">是</el-radio>
                          <el-radio :label="false">否</el-radio>
                        </el-radio-group>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item
                        label="商品大类"
                        prop="category1"
                        :rules="[{ required: true, message: `请输入商品大类`, trigger: 'blur' }]"
                      >
                        <el-input type="text" v-model="formData.category1" placeholder="请输入"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="6">
                      <el-form-item
                        label="商品小类"
                        prop="category2"
                        :rules="[{ required: true, message: `请输入商品小类`, trigger: 'blur' }]"
                      >
                        <el-input type="text" v-model="formData.category2" placeholder="请输入"></el-input>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item
                        label="商品名称"
                        prop="goodsName"
                        :rules="[{ required: true, message: `请输入商品名称`, trigger: 'blur' }]"
                      >
                        <el-input
                          type="textarea"
                          :rows="3"
                          v-model="formData.goodsName"
                          placeholder="请输入"
                        ></el-input>
                        <div class="hui">商品名称将显示在商品详情，让用户更直接了解商品内涵</div>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item label="商品描述" prop="describeText">
                        <el-input
                          type="textarea"
                          :rows="3"
                          v-model="formData.describeText"
                          placeholder="请输入"
                        ></el-input>
                        <div class="hui">商品描述将显示在商品详情，让用户更了解商品细节</div>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item
                        label="商品主图"
                        prop="imgUrl"
                        :rules="[{ required: true, message: `请上传商品主图`, trigger: 'change' }]"
                      >
                        <ImageUpload :fileList="formData.imgUrl" :limit="1" :isEdit="true" :fileType="['image']" />
                        <div class="suggest">建议尺寸800*800</div>
                      </el-form-item>
                    </el-col>
                    <el-col :span="12">
                      <el-form-item label="商品视频" prop="vedio">
                        <ImageUpload :fileList="formData.vedio" :limit="1" :isEdit="true" :fileType="['video']" />
                        <div class="suggest">建议视频宽高比16:9，建议时长9-30秒</div>
                      </el-form-item>
                    </el-col>
                    <el-col :span="24">
                      <el-form-item
                        label="轮播图"
                        prop="imgs"
                        :rules="[{ required: true, message: `请上传轮播图`, trigger: 'change' }]"
                      >
                        <ImageUpload :fileList="formData.imgs" :limit="6" :isEdit="true" :fileType="['image']" />
                        <div class="suggest">建议尺寸800*800，最多上传6张</div>
                      </el-form-item>
                    </el-col>
                  </div>
                  <div v-show="stepIndex == 1">
                    <el-col :span="24">
                      <el-form-item label="规格类型" prop="goodsLibrarySpecList" class="is-required">
                        <el-button size="mini" @click="add()" type="primary">添加规格</el-button>
                      </el-form-item>
                    </el-col>
                    <el-form ref="formData" :model="formData" label-width="110px" size="small">
                      <el-table
                        :data="formData.goodsLibrarySpecList"
                        element-loading-text="Loading"
                        border
                        fit
                        highlight-current-row
                        stripe
                      >
                        <el-table-column prop="" align="center" label="*大类">
                          <template slot-scope="scope">
                            <el-form-item
                              :prop="'goodsLibrarySpecList.' + scope.$index + '.mainName'"
                              :rules="[{ required: true, message: `请输入大类`, trigger: 'blur' }]"
                              label-width="0"
                            >
                              <el-input
                                type="text"
                                v-model="scope.row.mainName"
                                :disabled="isEdit != scope.$index"
                                placeholder="请输入"
                              ></el-input>
                            </el-form-item>
                          </template>
                        </el-table-column>
                        <el-table-column prop="" align="center" label="*小类">
                          <template slot-scope="scope">
                            <el-form-item
                              :prop="'goodsLibrarySpecList.' + scope.$index + '.smallName'"
                              :rules="[{ required: true, message: `请输入小类`, trigger: 'blur' }]"
                              label-width="0"
                            >
                              <el-input
                                type="text"
                                v-model="scope.row.smallName"
                                :disabled="isEdit != scope.$index"
                                placeholder="请输入"
                              ></el-input>
                            </el-form-item>
                          </template>
                        </el-table-column>
                        <el-table-column prop="" align="center" label="*规格型号">
                          <template slot-scope="scope">
                            <el-form-item
                              :prop="'goodsLibrarySpecList.' + scope.$index + '.specValue'"
                              :rules="[{ required: true, message: `请输入规格型号`, trigger: 'blur' }]"
                              label-width="0"
                            >
                              <el-input
                                type="text"
                                v-model="scope.row.specValue"
                                :disabled="isEdit != scope.$index"
                                placeholder="请输入"
                              ></el-input>
                            </el-form-item>
                          </template>
                        </el-table-column>
                        <el-table-column prop="" align="center" label="*参考销售价格">
                          <template slot-scope="scope">
                            <el-form-item
                              :prop="'goodsLibrarySpecList.' + scope.$index + '.price'"
                              :rules="[
                                { required: true, message: `请输入参考销售价格`, trigger: 'blur' },
                                {
                                  pattern: /^(([0-9]\d*)|([0][.]{1}[0-9]{0,2}[1-9]+)|([1-9]\d*[.]{1}[0-9]+))$/g,
                                  message: '请输入大于等于0的数',
                                  trigger: 'blur'
                                }
                              ]"
                              label-width="0"
                            >
                              <el-input
                                type="number"
                                v-model="scope.row.price"
                                :disabled="isEdit != scope.$index"
                                placeholder="请输入"
                              ></el-input>
                            </el-form-item>
                          </template>
                        </el-table-column>
                        <el-table-column prop="" align="center" label="*参考划线价格">
                          <template slot-scope="scope">
                            <el-form-item
                              :prop="'goodsLibrarySpecList.' + scope.$index + '.orgPrice'"
                              :rules="[
                                { required: true, message: `请输入参考划线价格`, trigger: 'blur' },
                                {
                                  pattern: /^(([0-9]\d*)|([0][.]{1}[0-9]{0,2}[1-9]+)|([1-9]\d*[.]{1}[0-9]+))$/g,
                                  message: '请输入大于等于0的数',
                                  trigger: 'blur'
                                }
                              ]"
                              label-width="0"
                            >
                              <el-input
                                type="number"
                                v-model="scope.row.orgPrice"
                                :disabled="isEdit != scope.$index"
                                placeholder="请输入"
                              ></el-input>
                            </el-form-item>
                          </template>
                        </el-table-column>
                        <el-table-column prop="" align="center" label="*参考成本价">
                          <template slot-scope="scope">
                            <el-form-item
                              :prop="'goodsLibrarySpecList.' + scope.$index + '.costPrice'"
                              :rules="[
                                { required: true, message: `请输入参考成本价`, trigger: 'blur' },
                                {
                                  pattern: /^(([0-9]\d*)|([0][.]{1}[0-9]{0,2}[1-9]+)|([1-9]\d*[.]{1}[0-9]+))$/g,
                                  message: '请输入大于等于0的数',
                                  trigger: 'blur'
                                }
                              ]"
                              label-width="0"
                            >
                              <el-input
                                type="number"
                                v-model="scope.row.costPrice"
                                :disabled="isEdit != scope.$index"
                                placeholder="请输入"
                              ></el-input>
                            </el-form-item>
                          </template>
                        </el-table-column>
                        <el-table-column prop="" align="center" label="*参考佣金">
                          <template slot-scope="scope">
                            <el-form-item
                              :prop="'goodsLibrarySpecList.' + scope.$index + '.shareAmount'"
                              :rules="[
                                { required: true, message: `请输入参考佣金`, trigger: 'blur' },
                                {
                                  pattern: /^(([0-9]\d*)|([0][.]{1}[0-9]{0,2}[1-9]+)|([1-9]\d*[.]{1}[0-9]+))$/g,
                                  message: '请输入大于等于0的数',
                                  trigger: 'blur'
                                }
                              ]"
                              label-width="0"
                            >
                              <el-input
                                type="number"
                                v-model="scope.row.shareAmount"
                                :disabled="isEdit != scope.$index"
                                placeholder="请输入"
                              ></el-input>
                            </el-form-item>
                          </template>
                        </el-table-column>
                        <el-table-column prop="" align="center" label="*参考内部佣金">
                          <template slot-scope="scope">
                            <el-form-item
                              :prop="'goodsLibrarySpecList.' + scope.$index + '.innerShareAmount'"
                              :rules="[
                                { required: true, message: `请输入参考内部佣金`, trigger: 'blur' },
                                {
                                  pattern: /^(([0-9]\d*)|([0][.]{1}[0-9]{0,2}[1-9]+)|([1-9]\d*[.]{1}[0-9]+))$/g,
                                  message: '请输入大于等于0的数',
                                  trigger: 'blur'
                                }
                              ]"
                              label-width="0"
                            >
                              <el-input
                                type="number"
                                v-model="scope.row.innerShareAmount"
                                :disabled="isEdit != scope.$index"
                                placeholder="请输入"
                              ></el-input>
                            </el-form-item>
                          </template>
                        </el-table-column>
                        <el-table-column prop="" align="center" label="*参考规格图片">
                          <template slot-scope="scope">
                            <el-form-item
                              :prop="'goodsLibrarySpecList.' + scope.$index + '.imgUrl'"
                              :rules="[{ required: true, message: `请上传参考规格图片`, trigger: 'change' }]"
                              label-width="0"
                            >
                              <div class="flex_ac">
                                <ImageUpload
                                  :fileList="scope.row.imgUrl"
                                  :limit="1"
                                  :download="false"
                                  :viewOnline="false"
                                  :isEdit="true"
                                  modType="text"
                                  :fileType="['image']"
                                />
                              </div>
                            </el-form-item>
                          </template>
                        </el-table-column>
                        <el-table-column label="操作" align="center" width="160">
                          <template slot-scope="scope">
                            <el-button
                              size="mini"
                              type="primary"
                              v-if="scope.$index != isEdit"
                              @click="edit(scope.$index)"
                              >编辑</el-button
                            >
                            <el-button size="mini" type="danger" @click="del(scope.$index)">删除</el-button>
                          </template>
                        </el-table-column>
                      </el-table>
                    </el-form>
                  </div>
                  <div v-show="stepIndex == 2">
                    <el-form-item
                      label="详情内容"
                      prop="content"
                      :rules="[{ required: true, message: `请输入详情内容`, trigger: 'change' }]"
                    >
                      <quillEditor v-model="formData.content"></quillEditor>
                      <input type="hidden" v-model="formData.content" />
                    </el-form-item>
                  </div>
                </el-row>
              </el-form>
            </div>
          </el-card>
        </div>
        <div class="footer">
          <el-button v-if="stepIndex > 0" size="mini" @click="up()">上一步</el-button>
          <el-button v-if="stepIndex < 2" size="mini" @click="next()">下一步</el-button>
          <el-button size="mini" @click="formConfirm(data.removeTab)" type="primary">提交</el-button>
          <el-button size="mini" @click="data.removeTab()">关闭</el-button>
        </div>
      </div>
    </template>
  </zj-tab-page>
</template>

<script>
import TemplatePage from '@/components/template/template-page-1.vue'
import import_mixin from '@/components/template/import_mixin.js'
import ImageUpload from '@/components/file-upload'
import { required, mobileRequired, mobile } from '@/components/template/rules_verify.js'
import { listPageV2, pageExport, save, del, getDetail, batch, sync } from '@/api/goodsWarehouse'
import operation_mixin from '@/components/template/operation_mixin.js'
import quillEditor from '@/components/v-quill-editor'
export default {
  components: {
    TemplatePage,
    ImageUpload,
    quillEditor
  },
  mixins: [import_mixin, operation_mixin],
  data() {
    return {
      // 表格属性
      tableAttributes: {
        // 启用勾选列
        selectColumn: true
      },
      // 表格事件
      tableEvents: {
        'selection-change': this.selectionChange
      },
      // 勾选选中行
      recordSelected: [],
      /** 表单变量 */
      formDialogType: 0,
      formDialogTitles: ['新增', '编辑'],
      formDialog: false,
      formData: {
        status: true,
        brandName: '',
        category1: '',
        category2: '',
        isVr: true,
        goodsName: '',
        describeText: '',
        imgUrl: [],
        vedio: [],
        imgs: [],
        content: '',
        goodsLibrarySpecList: []
      },
      rules: {},
      status: '',
      formType: 'add',
      formVisible: false,
      stepIndex: 0,
      isEdit: 0
    }
  },
  computed: {
    // 事件组合
    optionsEvensGroup() {
      return [
        [
          [
            this.optionsEvensAuth('add', {
              click: () => {
                this.openForm('add')
              }
            })
          ]
        ],
        [
          [
            this.optionsEvensAuth('openMore', {
              click: () => {
                this.openMore()
              }
            })
          ]
        ],
        [
          [
            this.optionsEvensAuth('closeMore', {
              click: () => {
                this.closeMore()
              }
            })
          ]
        ],
        [
          [
            this.optionsEvensAuth('synchronization', {
              click: () => {
                this.sync()
              }
            })
          ]
        ]
      ]
    },
    // 更多参数
    moreParameters() {
      return []
    },
    formItems() {
      return []
    }
  },
  methods: {
    // 列表请求函数
    getList(p, cb) {
      try {
        var pam = JSON.parse(JSON.stringify(p))
        pam.params.push({ param: 'a.status', compare: '=', value: this.status })
        cb && cb(pam)
        return listPageV2(pam)
      } catch (error) {
        console.log(error)
      }
    },
    // 列表导出函数
    exportList: pageExport,
    changeType() {
      this.$refs.pageRef.refreshList()
    },
    // 表格列解析渲染数据更改
    columnParsing(item, defaultData) {
      if (item.jname === 'imgUrl') {
        defaultData.render = (h, { row, index, column }) => {
          return (
            <div style="padding:6px;cursor: pointer;">
              {row.imgUrl
                ? row.imgUrl
                    .split(',')
                    .map(url => (
                      <el-image
                        src={this.$showImgUrl(url)}
                        preview-src-list={[this.$showImgUrl(url)]}
                        fit="fit"
                        style="width:60px;height:60px;"
                      />
                    ))
                : null}
            </div>
          )
        }
      }
      if (item.jname === 'goodsName') {
        defaultData.render = (h, { row, index, column }) => {
          return <div style="padding:6px;">{row.goodsName}</div>
        }
        defaultData.columnAttributes.width = 300
        console.log(defaultData, 11)
      }
      return defaultData
    },
    up() {
      this.stepIndex -= 1
    },
    next() {
      this.stepIndex += 1
    },
    add() {
      this.$refs.formData.validate(valid => {
        if (valid) {
          this.isEdit = 0
          this.formData.goodsLibrarySpecList.unshift({
            mainName: '',
            smallName: '',
            specValue: '',
            price: '',
            orgPrice: '',
            shareAmount: '',
            innerShareAmount: '',
            costPrice: '',
            imgUrl: []
          })
        }
      })
    },
    edit(index) {
      this.$refs.formData.validate(valid => {
        if (valid) {
          this.isEdit = index
        }
      })
    },
    del(index) {
      this.formData.goodsLibrarySpecList.splice(index, 1)
    },
    // 监听勾选变化
    selectionChange(data) {
      this.recordSelected = data
    },
    openMore() {
      if (this.recordSelected.length == 0) {
        return this.$message.warning('请至少勾选一条数据！')
      }
      this.batch(
        this.recordSelected.map(item => {
          return item.goodsLibraryId
        }),
        true
      )
    },
    closeMore() {
      if (this.recordSelected.length == 0) {
        return this.$message.warning('请至少勾选一条数据！')
      }
      this.batch(
        this.recordSelected.map(item => {
          return item.goodsLibraryId
        }),
        false
      )
    },
    batch(goodsLibraryIds, statusEnum) {
      console.log(goodsLibraryIds)
      this.$confirm('请确认是否批量操作选中的数据, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        batch({
          goodsLibraryIds: goodsLibraryIds.join(','),
          statusEnum
        }).then(res => {
          this.$message({ type: 'success', message: statusEnum ? '批量开启成功！' : '批量关闭成功！' })
          this.$refs.pageRef.refreshList()
        })
      })
    },
    sync() {
      const loading = this.$loading({
        lock: true,
        text: 'Loading',
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)'
      })
      sync().then(res => {
        if (res.code == 200) {
          this.$message({ type: 'success', message: `同步成功!` })
          this.$refs.pageRef.refreshList()
        } else {
          this.$message({ type: 'error', message: res.message })
        }
        loading.close()
      })
    },
    // 表格操作列
    operation() {
      return this.operationBtn({
        edit: {
          btnType: 'text',
          click: ({ row, index, column }) => {
            this.openForm('edit', row.goodsLibraryId)
          }
        },
        del: {
          btnType: 'text',
          prompt: '确定删除吗？',
          click: ({ row, index, column }) => {
            del({
              goodsLibraryId: row.goodsLibraryId
            }).then(() => {
              this.$message({
                type: 'success',
                message: '删除成功!'
              })
              this.$refs.pageRef.refreshList()
            })
          }
        }
      })
    },
    // 打开 新增编辑 网点表单
    openForm(type, goodsLibraryId) {
      this.$refs.tabPage.addTab({
        // 对应显示的模块
        activeKey: type,
        // 唯一标识
        key: type,
        // 页签名称
        label: {
          edit: '编辑',
          add: '新增'
        }[type],
        // 打开时事件
        triggerEvent: () => {
          this.formCancel()
          this.$nextTick(() => {
            this.formType = type
            this.formVisible = true
            if (type == 'add') {
              this.formDialogType = 0
            } else if (type == 'edit') {
              this.formDialogType = 1
              getDetail({
                goodsLibraryId
              }).then(res => {
                let imgs = []
                let goodsLibrarySpecList = []
                res.data.imgs.split(',').forEach(item => {
                  imgs.push({
                    url: item
                  })
                })
                res.data.goodsLibrarySpecList.forEach(item => {
                  goodsLibrarySpecList.push({
                    ...item,
                    imgUrl: item.imgUrl ? [{ url: item.imgUrl }] : []
                  })
                })
                Object.assign(this.formData, res.data, {
                  imgUrl: res.data.imgUrl ? [{ url: res.data.imgUrl }] : [],
                  imgs: res.data.imgs ? imgs : [],
                  vedio: res.data.vedio ? [{ url: res.data.vedio }] : [],
                  goodsLibrarySpecList
                })
                console.log(this.formData, imgs)
              })
            }
          })
        },
        // 关闭时事件
        closeEvent: () => {}
      })
    },
    formCancel() {
      this.formVisible = false
      this.$refs?.formRef?.resetFields()
      this.$data.formData = this.$options.data().formData
    },
    formConfirm(cancel) {
      let imgs = this.formData.imgs.map(item => {
        return item.url
      })
      let goodsLibrarySpecList = []
      this.formData.goodsLibrarySpecList.forEach(item => {
        goodsLibrarySpecList.push({
          ...item,
          imgUrl: item.imgUrl.length > 0 ? item.imgUrl[0].url : ''
        })
      })
      this.$refs.formRef.validate((valid, invalidFields, errLabels) => {
        if (valid) {
          this.$refs.formData.validate((valid, invalidFields, errLabels) => {
            if (valid) {
              save({
                ...this.formData,
                imgUrl: this.formData.imgUrl.length > 0 ? this.formData.imgUrl[0].url : '',
                imgs: this.formData.imgs.length > 0 ? imgs.join(',') : '',
                vedio: this.formData.vedio.length > 0 ? this.formData.vedio[0].url : '',
                goodsLibrarySpecList
              }).then(res => {
                this.stepIndex = 0
                this.$message({
                  type: 'success',
                  message: `${this.formDialogTitles[this.formDialogType]}成功!`
                })
                cancel('list')
                this.$refs.pageRef.refreshList()
              })
            } else {
              this.stepIndex = 1
            }
          })
        } else {
          if (this.formData.goodsLibrarySpecList.length == 0) {
            this.stepIndex = 1
            this.$message({
              type: 'warning',
              message: '请添加规格类型！'
            })
          } else if (!this.formData.content) {
            this.stepIndex = 2
            this.$message({
              type: 'warning',
              message: '请输入商品内容详情！'
            })
          } else {
            this.stepIndex = 0
          }
        }
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.page {
  padding: 20px;
  padding-bottom: 60px;
  box-sizing: border-box;
}
.flex_ac {
  display: flex;
  align-items: center;
}
.box-card {
  margin-top: 30px;
}
.hui {
  color: #888888;
}
.suggest {
  display: inline-block;
  padding: 0 10px;
  margin-top: 10px;
  background-color: #ffdee5;
  color: #cd1e46;
}
.footer {
  position: fixed;
  bottom: 0;
  left: 0;
  z-index: 1;
  width: 100%;
  background: #fff;
  padding: 15px 40px;
  box-sizing: border-box;
  transition: all 0.28s;
  text-align: right;
  box-shadow: 0 2px 5px 0 rgb(0 0 0 / 50%), 0 2px 5px 0 rgb(0 0 0 / 10%);

  &.hideSidebar {
    margin-left: 54px;
    width: calc(100vw - 54px);
  }

  &.openSidebar {
    margin-left: 210px;
    width: calc(100vw - 210px);
  }

  .tips {
    font-size: 12px;
    color: red;
    margin-top: 10px;
  }
}
</style>
