<template>
  <div class='system-menu card'>
    <div class='header'>
      <el-form
        size='mini'
        :inline='true'
        label-width='80px'
      >
        <el-form-item label>
          <el-button
            type='primary'
            @click='showDialog({ id: 0 }, 2)'
          >
            新增
          </el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class='table-wrap' v-loading='loading'>
      <table-view
        :tableColumns='tableColumns'
        rowKey='id'
        :serialNumber='true'
        :treeConfig="{
          children: 'children',
          reserve: true,
        }"
        :sourceData='sourceData'
      ></table-view>
    </div>
    <div class="pagination">
      <el-pagination
        layout="sizes, total, prev, pager, next, jumper"
        background
        :total="total"
        :page-size="pageSize"
        :current-page="currentPage"
        @size-change="sizeChange"
        @current-change="onCurrentChange"
      >
      </el-pagination>
    </div>
    <el-dialog
      title="新增"
      :visible.sync='dialogVisible'
      :close-on-click-modal='false'
      :before-close='beforeClose'
      width='1000px'
    >
      <el-form
        size='mini'
        :inline='true'
        label-width='120px'
        :rules='rules'
        ref='editForm'
        :model='editForm'
      >
        <el-form-item class="title_width" prop="title" label="更新标题">
          <el-input type="textarea" v-model="editForm.title" placeholder="请输入更新标题"></el-input>
        </el-form-item>
        <el-form-item  class="title_width" prop="content" label="更新内容">
          <el-input type="textarea" rows="10" v-model="editForm.content" placeholder="请输入更新内容"></el-input>
        </el-form-item>
        <el-form-item prop="version" label="版本号">
          <el-input class="item_width" v-model="editForm.version" placeholder="请输入版本号"></el-input>
        </el-form-item>
        <el-form-item prop="forcedUpdate" label="是否强制更新">
          <el-radio-group class="item_width" v-model="editForm.forcedUpdate">
            <el-radio :label="0">否</el-radio>
            <el-radio :label="1">是</el-radio>
          </el-radio-group>
        </el-form-item>
        <!-- 上传多个app文件 -->
        <el-form-item label="上传文件">
            <!-- accept=".apk,.ipa" -->
          <el-upload
            action
            :http-request="handleCustom"
            :on-change="handleChange"
            :on-remove="handleRemove"
            :before-upload="beforeUpload"
            :file-list="fileList"
            list-type="text"
          >
          <div class="upload-file">
            <el-button class="el-upload">
                <i class="el-icon-plus"></i>
            </el-button>
          </div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot='footer'>
        <el-button size='small' @click='clone'
        >取 消
        </el-button
        >
        <el-button
          size='small'
          type='primary'
          @click='submit'
        >保 存
        </el-button
        >
      </div>
    </el-dialog>
  </div>
</template>
<script>
import tableView from '@/common/components/base/tableView.vue'
import { erpProductionAssistantManage, erpProductionAssistantManageListPage, deleteErpProductionAssistantManage } from '../../common/api/production/assistantManage'

export default {
  name: 'saasMenu',
  components: {
    tableView,
  },
  data() {
    return {
      loading: false,
      sourceData: [
       { id: 1, version: '1.1.2', title: '更新字段1', content: '内容', forcedUpdate: 0, businessType: 'production_assistant', fileList: [] },
       { id: 2, version: '1.1.2', title: '更新字段2', content: '内容', forcedUpdate: 1, businessType: 'production_assistant', fileList: [] }
      ],
      dialogVisible: false,
      editForm: {
        version: '',
        title: '',
        content: '',
        forcedUpdate: 0,
        // businessType: 'production_assistant'
      },
      fileList: [],
      rules: {
        // 自定义版本号的校验规则
        version: [
          { required: true, message: '请输入版本号', trigger: 'blur' },
          {
            validator: (rule, value, callback) => {
              if (!/^\d+\.\d+\.\d+$/.test(value)) {
                callback(new Error('版本号格式不正确'))
              } else {
                callback()
              }
            },
            trigger: 'blur',
          },
        ],
        title: [
          { required: true, message: '请输入更新标题', trigger: 'blur' },
        ],
        content: [
          { required: true, message: '请输入更新内容', trigger: 'blur' },
        ],
      },
      total: 1,
      currentPage: 1,
      pageSize: 10,
    }
  },
  computed: {
    tableColumns() {
      return [
        {
          label: '更新标题',
          key: 'title',
          width: '',
        },
        {
          label: '版本号',
          key: 'version',
          width: '80'
        },
        {
          label: '更新内容',
          key: 'content',
          width: '',
        },
        {
          label: ' 是否强制更新',
          key: 'forcedUpdate',
          width: '100',
          render: item => {
            return item.forcedUpdate === 1 ? '是' : '否'
          }
        },
        {
          label: '应用软件名称',
          key: 'businessType',
          width: '100',
          render: item => {
            return item ? '生产助手' : ''
          }
        },
        {
          label: '操作',
          key: '',
          width: '80',
          // align: 'left',
          render: item => (
            <div>
              <el-button
                size='mini'
                type='text'
                class="edit"
                onClick={() => this.remove(item)}
              >
                删除
              </el-button>
            </div>
          ),
        },
      ]
    },
  },
  created() {
    this.getProductionAssistantList()
  },
  methods: {
    async getProductionAssistantList() {
      this.loading = true
      try {
        const { data: erpProductionAssistantManageRes, code } = await erpProductionAssistantManageListPage({
          currentPage: this.currentPage,
          pageSize: this.pageSize,
        })
        if (code === 200) {
          console.log('erpProductionAssistantManageRes:>>', erpProductionAssistantManageRes)
          this.sourceData = erpProductionAssistantManageRes.records
          this.total = erpProductionAssistantManageRes.total
        }
      } catch (error) {
        console.log('error:>>', error)
      } finally {
        this.loading = false
      }
    },
    async deleteProductionAssistant(ids) {
      const deleteProductionRes = await deleteErpProductionAssistantManage(ids)
      if (deleteProductionRes.code === 200) {
        this.$message({
          type: 'success',
          message: '删除成功!',
        })
        setTimeout(() => {
          this.getProductionAssistantList()
        }, 1000)
      }
    },
    formFile(fileList, reset) {
      const formData = new FormData()
      fileList.forEach(file => {
        formData.append('fileList', file.raw)
      })
      for (const key in reset) {
        formData.append(key, reset[key])
      }
      return formData
    },
    showDialog() {
      this.dialogVisible = true
    },
    resetForm() {
      for (const key in this.editForm) {
        if (key === 'forcedUpdate') {
          this.editForm[key] = 0
          continue
        }
        if (key === 'businessType') {
          this.editForm[key] = 'production_assistant'
          continue
        }
        this.editForm[key] = ''
      }
      this.fileList = []
    },
    clone() {
      this.resetForm()
      this.dialogVisible = false
    },
    submit() {
      // 验证表单
      this.$refs.editForm.validate(async valid => {
        if (valid) {
          // 提交表单
          if (this.fileList?.length === 0) {
            return this.$message({
              type: 'warning',
              message: '请上传文件!',
            })
          }
          const productionAssistantParams = this.formFile(this.fileList, { ...this.editForm, businessType: 'production_assistant' })
          try {
            const res = await erpProductionAssistantManage(productionAssistantParams)
            console.log('提交表单:>>> ', res, '\nproductionAssistantParams:>>', productionAssistantParams)
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: '保存成功!',
              })
              this.resetForm()
              this.getProductionAssistantList()
              this.dialogVisible = false
            }
          } catch (error) {
            console.log('error:>>', error)
          }
        }
      })
    },
    beforeClose(done) {
      this.resetForm()
      done()
    },
    remove({ id }) {
        this.$confirm('是否删除该数据', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
        }).then(() => {
          this.deleteProductionAssistant(id)
        })
    },
    handleCustom(file) {
      this.$message({
        type: 'success',
        message: '上传成功!',
      })
    },
    handleChange(file, fileList) {
      this.fileList = fileList
    },
    beforeUpload(file) {
      const isLt2M = file.size / 1024 / 1024 < 50
      if (!isLt2M) {
        this.$message.error('上传文件大小不能超过 50MB!')
        return false
      }
      return isLt2M
    },
    handleRemove(file, fileList) {
      this.fileList = fileList
    },
    sizeChange(pageSize) {
      this.pageSize = pageSize
      this.getProductionAssistantList()
    },
    onCurrentChange(currentPage) {
      this.currentPage = currentPage
      this.getProductionAssistantList()
    },
  },
}
</script>
<style lang='scss' scoped>
.system-menu {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 10px 20px 0;
  overflow: hidden;
  .item_width {
    width: 220px;
  }
  .title_width {
    display: flex;
  }
}
.table-wrap {
  background: #fff;
  flex: 1;
  overflow: hidden;
}

.system-menu:deep() .el-form-item__content {
  flex: 1;
}
.radioGroup {
  .el-radio {
    margin-right: 15px !important;
  }
}
.edit {
  color: #fff; /* 字体颜色 */
  background-color: #409EFF; /* 背景颜色 */
  border-radius: 4px; /* 圆角 */
  cursor: pointer; /* 鼠标悬停时显示手型 */
  transition: background-color 0.3s; /* 背景颜色过渡效果 */
}

.edit:hover {
  background-color: #66b1ff; /* 鼠标悬停时的背景颜色 */
}

.upload-file {
  .el-upload {
    padding: 70px;
    border-radius: 6px;
    background-color: #fff;
    border: 1px dashed #d9d9d9;
  }
  :deep() .el-button {
    font-size: 28px;
    color: #8c939d;
    text-align: center;
  }
}
</style>
