<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="editForm.id?'编辑':'新增'"
      :visible.sync='dialogVisible'
      :close-on-click-modal='false'
      :before-close='beforeClose'
      width='1000px'

    >
      <div  v-loading="saveLoading">
        <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>
          <div class="el-row" style="width: 100%;">
            <el-form-item class="el-col-11" 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>
            <el-form-item class="el-col-11" prop="fullUpdate" label="是否全量更新">
              <el-radio-group class="item_width" v-model="editForm.fullUpdate">
                <el-radio :label="0">否</el-radio>
                <el-radio :label="1">是</el-radio>
              </el-radio-group>
            </el-form-item>
          </div>

          <!-- 上传多个app文件 -->
          <el-form-item required  label="上传文件">
            <!-- accept=".apk,.ipa" -->
            <el-upload
              action
              :http-request="handleCustom"
              :multiple="false"
              :on-change="handleChange"
              :on-remove="handleRemove"
              :file-list="fileList"
              list-type="text"
            >
              <el-button type="primary">
                上传文件
              </el-button>
            </el-upload>
          </el-form-item>
        </el-form>
      </div>
      <div slot='footer'>
        <el-button :disabled="saveLoading" size='small' @click='clone'
        >取 消
        </el-button
        >
        <el-button
          size='small'
          type='primary'
          :disabled="saveLoading"
          @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,
      saveLoading: false,
      sourceData: [],
      dialogVisible: false,
      editForm: {
        version: '',
        title: '',
        content: '',
        forcedUpdate: 0,
        fullUpdate: 1

        // 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'
          }
        ],
        thirdWarehouseType: [
          {
            required: true,
            message: '请选择更新类型',
            trigger: 'change'
          }
        ],
        content: [
          {
            required: true,
            message: '请输入更新内容',
            trigger: 'blur'
          }
        ]
      },
      total: 1,
      currentPage: 1,
      pageSize: 10
    }
  },
  computed: {
    tableColumns() {
      return [
        {
          label: '版本号',
          key: 'version',
          width: '100'
        },
        {
          label: '更新标题',
          key: 'title',
          width: ''
        },

        {
          label: '更新内容',
          key: 'content',
          width: ''
        },
        {
          label: '是否强制更新',
          key: 'forcedUpdate',
          width: '140',
          render: item => {
            return item.forcedUpdate === 1 ? '是' : '否'
          }
        },
        {
          label: '是否全量更新',
          key: 'forcedUpdate',
          width: '140',
          render: item => {
            return item.fullUpdate === 1 ? '是' : '否'
          }
        },
        {
          label: '应用软件名称',
          key: 'businessType',
          width: '100',
          render: item => {
            return item ? '生产助手' : ''
          }
        },
        {
          label: '操作',
          key: '',
          width: '120',
          // align: 'left',
          render: item => (
            <div>
               <span title="删除" class="icon-view ">
                <i
                  style="color:#F56C6C"
                  class="el-icon-delete"
                  onClick={() => this.remove(item)}
                ></i>
              </span>
            </div>
          )
        }
      ]
    }
  },
  created() {
    this.getProductionAssistantList()
  },
  methods: {
    async getProductionAssistantList() {
      this.loading = true
      try {
        const {
          data: erpProductionAssistantManageRes,
          code
        } = await erpProductionAssistantManageListPage({
          currentPage: this.currentPage,
          businessType: 'production_assistant',
          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: '请上传文件!'
            })
          }
          this.saveLoading = true
          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.saveLoading = false
              this.resetForm()
              await this.getProductionAssistantList()
              this.dialogVisible = false
            } else {
              this.saveLoading = false
            }
          } catch (error) {
            this.saveLoading = false
            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
    },
    update(row) {
      this.editForm = row
      this.dialogVisible = true
      console.log(row)
    },
    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;
  }

  .el-button {
    font-size: 28px;
    color: #8c939d;
    text-align: center;
  }
}
</style>
