<template>
  <el-main class="bg_white" style="min-height: calc(100% - 80px);">
    <el-row class="title_box">
      <el-col :span="24">
        <!-- <el-button type="primary" @click="handleEdit('', 'add')" :disabled="data.language_id !== 1">新增分类</el-button> -->
        <el-button type="primary" @click="handleEdit('', 'add')">
          新增分类
        </el-button>
      </el-col>
    </el-row>
    <!---产品列表-->
    <div class="table" style="margin-bottom: 40px;">
      <el-table
        :data="data.list"
        border
        row-key="id"
        :tree-props="{ children: 'children' }"
      >
        <el-table-column prop="id" label="ID" width="200"></el-table-column>
        <el-table-column
          label="ERP编码"
          prop="erp_code"
          width="250"
        ></el-table-column>
        <el-table-column
          label="分类图标"
          prop="icon"
          align="center"
          width="250"
        >
          <template #default="scope">
            <img
              :src="scope.row.icon ? scope.row.icon : defaulImg"
              @error="
                (e) => {
                  e.target.src = defaulImg
                }
              "
              style="width: 40px; height: 40px;"
            />
          </template>
        </el-table-column>
        <el-table-column label="分类名称" prop="name">
          <template #default="scope">
            <span v-if="scope.row.language_id == 1">{{ scope.row.name }}</span>
            <el-input
              v-model="scope.row.name"
              placeholder="请输入分类名称"
              @change="changeName(scope.row)"
              v-else
            />
          </template>
        </el-table-column>
        <el-table-column label="创建时间" prop="create_time"></el-table-column>
        <el-table-column
          fixed="right"
          width="150"
          label="操作"
          prop=""
          align="center"
        >
          <template #default="scope">
            <el-button
              title="编辑"
              type="primary"
              @click="handleEdit(scope.row, 'edit')"
            >
              编辑
            </el-button>
            <!-- <el-button title="删除" type="primary" @click="handleDel(scope.row)" :disabled="scope.row.language_id !== 1"> -->
            <el-button
              title="删除"
              type="primary"
              @click="handleDel(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
      <!-- <el-pagination class="m-b-20 m-t-20" :current-page="data.query_form.page" :page-sizes="[10, 20, 30]"
        :page-size="data.query_form.size" layout="total, sizes, prev, pager, next, jumper" :total="data.count"
        @size-change="handleSizeChange" @current-change="handleCurrentChange">
      </el-pagination> -->
    </div>
    <!--图片放大弹窗-->
    <el-dialog v-model="data.dialogVisible">
      <el-image width="100%" :src="data.dialogImg" alt></el-image>
    </el-dialog>
    <!--新增分类-->
    <el-dialog
      v-model="data.editCate"
      :show-close="true"
      :title="data.dialogTit"
      width="440px"
      center
    >
      <el-form ref="edit_form" :model="data.edit_form" label-width="110px">
        <el-form-item label="ERP编码" required>
          <el-input
            v-model="data.edit_form.erp_code"
            maxlength="100"
            style="width: 80%;"
          />
        </el-form-item>
        <el-form-item label="分类名称" required>
          <el-input
            v-model="data.edit_form.name"
            maxlength="100"
            style="width: 80%;"
          />
        </el-form-item>
        <el-form-item label="分类级别">
          <el-select
            v-model="data.edit_form.level"
            placeholder=""
            style="width: 80%;"
            @change="levelList"
            :disabled="data.editDisabled"
          >
            <el-option
              :label="item.name"
              :value="item.value"
              :key="index"
              v-for="(item, index) in data.typeCascdin"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="上级分类">
          <el-select
            v-model="data.edit_form.pid"
            placeholder=""
            style="width: 80%;"
            :disabled="data.disabled"
            @change="changeCataCom"
          >
            <el-option
              :label="item.name"
              :value="item.id"
              :key="index"
              v-for="(item, index) in data.cataList"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="产品单位" required v-if="data.edit_form.level == 3">
          <el-select
            v-model="data.edit_form.unit"
            style="width: 80%;"
          >
            <el-option
              :label="item.unit_name"
              :value="item.id"
              :key="index"
              v-for="(item, index) in data.utillist"
            />
          </el-select>
        </el-form-item>
        <el-form-item
          label="税收分类编码"
          required
          v-if="data.edit_form.level == 3"
        >
          <el-input
            v-model="data.edit_form.tax_category_code"
            maxlength="19"
            style="width: 80%;"
            @input="ssflhandleInput"
          />
        </el-form-item>
        <el-form-item label="启用批号" v-if="data.edit_form.level == 3">
          <el-switch
            v-model="data.edit_form.enable_lot_numberBoolean"
            active-color="#409EFF"
            inactive-color="#DCDFE6"
          ></el-switch>
        </el-form-item>
        
        <!-- <el-form-item label="分类图标">
          <el-upload
            ref="upload"
            :file-list="data.defaultImg"
            :action="data.api_upload_url"
            list-type="picture-card"
            :with-credentials="true"
            name="images"
            :data="data.icon"
            :on-success="
              function (res, file, file_list) {
                return handleSuccess(res, file, file_list, data.edit_form)
              }
            "
            :on-preview="handlePreview"
            :limit="data.limit"
            :on-remove="
              function (file, file_list) {
                return handleRemove(file, file_list, data.edit_form)
              }
            "
            accept=".jpg,.png"
            :on-exceed="onexceed"
          >
            <i class="el-icon-plus"></i>
          </el-upload>
        </el-form-item> -->
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="cancelClick">取消</el-button>
          <el-button type="primary" @click="comfirmClick">确定</el-button>
        </span>
      </template>
    </el-dialog>
    <!--删除提醒-->
    <el-dialog
      v-model="data.deleteModal"
      title="删除分类"
      :show-close="true"
      width="440px"
    >
      <div class="del_text">确定删除已选择的分类吗？</div>
      <template #footer>
        <div class="text-r">
          <el-button type="primary" plain @click="cancel">取消</el-button>
          <el-button type="primary" @click="deleteClick">确认</el-button>
        </div>
      </template>
    </el-dialog>
  </el-main>
</template>
<script>
import { reactive, onMounted, ref, getCurrentInstance } from 'vue'
import Request from '@/utils/request.js'
import { ElMessage, ElLoading } from 'element-plus'
import { useStore } from 'vuex'
import { useRouter } from 'vue-router'
import defaulImg from '@/assets/defaulImg.jpg'
export default {
  name: 'Category',
  setup() {
    const { proxy } = getCurrentInstance()
    const router = useRouter()
    let store = useStore()
    let data = reactive({
      utillist:[],// 产品单位
      typeCascdin: [
        { name: '一级分类', value: 1 },
        { name: '二级分类', value: 2 },
        { name: '三级分类', value: 3 },
      ],
      api_upload_url:
        process.env.VUE_APP_API_BASEURL + 'admin/v1/category/upload',
      cdn: store.state.user.cdn,
      show_img: '',
      deleteModal: false,
      row: {},
      icon: {
        type: 'images',
        language_id: 1,
      },
      defaultImg: [],
      limit: 1,
      dialogVisible: false,
      disabled: false,
      dialogImg: '',
      dialogTit: '',
      fileList: [],
      cataList: [],
      count: 0,
      editCate: false,
      language_id: 0,
      list: [],
      cate_id: 0,
      edit_form: {
        id: '',
        erp_code: '',
        name: '',
        icon: '',
        level: '',
        pid: '',
        language_id: 1,
        erp_pid: 222389,
        erp_id: 0,
        tax_category_code: '', // 税收分类编码
        enable_lot_number: '', //是否启用批号管理：0为否，1为是
        enable_lot_numberBoolean: false, //是否启用批号管理布尔值
        unit:'',// 产品单位
      },
      editIcon: {
        icon: '',
        id: 1,
        language_id: 1,
        name: '',
        pid: 0,
        status: 0,
      },
      query_form: {
        page: 1,
        size: 10,
      },
      editDisabled: false,
      lockClear: false,
    })
    onMounted(() => {
      setTimeout(() => {
        data.cdn = store.state.user.cdn
        data.language_id = store.state.user.language.id
        data.icon.language_id = store.state.user.language.id
        getList()
        getutillist()
      }, 200)
    })
    const request = new Request()
    // 获取计量单位数据下拉
    const getutillist = () => { 
      request
        .get('v1/unit/list')
        .then((res) => { 
         data.utillist=res.data
        })
    }
    const getList = () => {
      data.list = []
      console.log('store.state.user.cdn', store.state.user.cdn)
      request
        .get('v1/category', { language_id: data.language_id })
        .then((res) => {
          if (res.status == 200) {
            data.list = res.data
            data.count = res.data.count
            data.list.forEach((item) => {
              if (item.icon != '') {
                item.icon = data.cdn + item.icon
                item.uid = item.id
                // item.show_img = [
                //   {
                //     uid: item.id,
                //     url: data.cdn + item.icon
                //   }
                // ]
              }
              if (item.children) {
                item.children.forEach((item1) => {
                  if (item1.icon != '') {
                    item1.icon = data.cdn + item1.icon
                    item1.uid = item1.id
                    // item1.show_img = [
                    //   {
                    //     uid: item1.id,
                    //     url: data.cdn + item1.icon
                    //   }
                    // ]
                  }
                  if (item1.children) {
                    item1.children.forEach((item2) => {
                      if (item2.icon != '') {
                        item2.icon = data.cdn + item2.icon
                        item2.uid = item2.id
                        // item2.show_img = [
                        //   {
                        //     uid: item2.id,
                        //     url: data.cdn + item2.icon
                        //   }
                        // ]
                      }
                    })
                  }
                })
              }
            })
          } else {
            ElMessage({
              type: 'error',
              message: res.message,
            })
          }
        })
    }
    const errorHandler = () => true
    const handleSizeChange = (size) => {
      data.query_form.size = size
      getList()
    }
    const handleCurrentChange = (page) => {
      data.query_form.page = page
      getList()
    }
    const handlePreview = (file) => {
      data.dialogImg = file.url
      data.dialogVisible = true
    }
    const onexceed = (file, fileList) => {
      if (fileList.length + file.length > data.limit) {
        ElMessage({
          type: 'error',
          message: '最多可上传1张分类图标!',
        })
        return false
      }
    }
    //上传成功
    const handleSuccess = (res, file, fileList, item) => {
      data.cate_id = item.id
      ;(data.editIcon = {
        icon: res.data[0].r_path,
        id: item.id,
        language_id: item.language_id,
        name: item.name,
        erp_code: item.erp_code,
        pid: item.pid,
        status: item.status,
      }),
        (data.lockClear = false)
      item.icon = [
        {
          uid: item.id,
          url: res.data[0].url,
        },
      ]
      //   changeIcon(data.editIcon)
    }
    //删除图标
    const handleRemove = (file, file_list, item) => {
      data.defaultImg = []
      data.lockClear = true
    }
    const changeIcon = (params) => {
      request.put('v1/category/' + data.cate_id, params).then((res) => {
        if (res.status == 200) {
          ElMessage({
            type: 'success',
            message: res.message,
          })
        }
      })
    }
    // 税收编码，仅可输入纯数字，19位
    const ssflhandleInput = (event) => {
      // 获取输入值
      const value = event
      // 使用正则表达式来限制输入为纯数字且不超过19位
      const newValue = value.replace(/[^\d]/g, '').slice(0, 19)
      // 更新响应式引用
      data.edit_form.tax_category_code = newValue
    }
    //修改分类名称
    const changeName = (row) => {
      // data.cate_id = row.id
      // data.editIcon = {
      //   language_id: row.language_id,
      //   name: row.name
      // }
      // changeIcon(data.editIcon)
    }
    //编辑分类
    const handleEdit = (row, type) => {
      clearData()
      data.defaultImg = []
      if (type == 'edit') {
        proxy.$http
          .get('v1/category/' + row.id, {
            language_id: store.state.user.language.id,
          })
          .then((res) => {
            if (res.status == 200) {
              // console.log('编辑获取详情', res.data)
              data.type = 'edit'
              data.dialogTit = '编辑分类'
              data.edit_form.id = row.id
              data.edit_form.erp_pid = res.data.erp_pid
              data.edit_form.erp_id = res.data.erp_id
              data.edit_form.language_id = row.language_id
              data.edit_form.name = res.data.name
              data.edit_form.erp_code = res.data.erp_code
              data.edit_form.icon = res.data.icon
              data.edit_form.tax_category_code = res.data.tax_category_code
              data.edit_form.unit = res.data.unit
              data.edit_form.enable_lot_number = res.data.enable_lot_number
              data.edit_form.enable_lot_numberBoolean= res.data.enable_lot_number==0?false:res.data.enable_lot_number==1?true:''
              data.editDisabled = true
              row.icon
                ? (data.defaultImg = [{ name: row.name, url: row.icon }])
                : (data.defaultImg = [])
              data.edit_form.level = Number(res.data.level)
              levelList(data.edit_form.level)
              data.edit_form.level == 1
                ? (data.disabled = true)
                : (data.disabled = false)
              data.edit_form.level == 1
                ? (data.edit_form.pid = '')
                : (data.edit_form.pid = res.data.pid)
              data.editCate = true
            }
          })
      } else {
        if (store.state.user.language.id == 1) {
          data.type = 'add'
          data.dialogTit = '新增分类'
          data.edit_form.level = 1
          data.disabled = true
          data.editDisabled = false
          data.editCate = true
          data.edit_form.erp_id = 0
          data.edit_form.erp_pid = 222389
        } else {
          proxy.$message.error('请切回简体中文')
        }
      }
    }
    //获取上级分类
    const levelList = (val) => {
      // data.edit_form.pid = ''
      if (val == 1) {
        data.disabled = true
      } else {
        data.disabled = false
        request
          .get('v1/category', { language_id: data.language_id, level: val - 1 })
          .then((res) => {
            if (res.status == 200) {
              data.cataList = res.data
              ElMessage({
                type: 'success',
                message: res.message,
              })
            } else {
              ElMessage({
                type: 'error',
                message: res.message,
              })
            }
          })
      }
    }
    // 上级分类 切换
    const changeCataCom = (val) => {
      if (data.cataList.length > 0)
        data.cataList.forEach((el) => {
          el.id == val ? (data.edit_form.erp_pid = el.erp_id) : ''
        })
    }
    // 取消关闭弹窗
    const cancelClick = () => {
      data.editCate = false
    }
    //取消
    const cancel = () => {
      data.deleteModal = false
      clearData()
    }
    //删除
    const handleDel = (row) => {
      if (store.state.user.language.id == 1) {
        data.row = row
        data.deleteModal = true
      } else {
        proxy.$message.error('请切回简体中文')
      }
    }
    const deleteClick = () => {
      let pathUrl = 'v1/category/' + data.row.id
      request
        .delete(pathUrl + '?language_id=' + store.state.user.language.id)
        .then((res) => {
          if (res.status == 200) {
            // console.log('res', res)
            ElMessage({
              type: 'success',
              message: res.message,
            })
            getList()
          } 
           data.deleteModal = false
        })
    }
    //确认修改
    const comfirmClick = async () => {
      if (data.edit_form.level == 3 && !data.edit_form.tax_category_code) {
        proxy.$message.error('请先填写税收分类编码！')
        return
      }
       if (data.edit_form.level == 3 && !data.edit_form.unit) {
        proxy.$message.error('计量单位为必填')
        return
      }
      data.edit_form.enable_lot_number =
        data.edit_form.level == 3
          ? data.edit_form.enable_lot_numberBoolean
            ? 1
            : 0
          : ''
      if (data.type == 'edit') {
        if (typeof data.edit_form.icon == 'string') {
          data.edit_form.icon =
            'dev_api_product' + data.edit_form.icon.split('dev_api_product')[1]
        } else {
          data.edit_form.icon =
            'dev_api_product' +
            data.edit_form.icon[0].url.split('dev_api_product')[1]
        }
        if (data.lockClear) {
          data.edit_form.icon = ''
        }
        try {
          await request
            .put('v1/category/' + data.edit_form.id, data.edit_form)
            .then((res) => {
              if (res.status == 200) {
                data.editCate = false
                getList()
                ElMessage({
                  type: 'success',
                  message: res.message,
                })
              }
            })
        } catch (error) {
          data.editCate = false
          ElMessage({
            type: 'error',
            message: '修改失败',
          })
        }
      } else {
        if (data.edit_form.level == 2 || data.edit_form.level == 3) {
          if (data.edit_form.pid) {
            categoryCom()
          } else {
            proxy.$message.error('请先选择上级分类')
          }
        } else {
          categoryCom()
        }
      }
    }
    // 分类级别 - 上级分类
    const categoryCom = () => {
      data.edit_form.id = ''
      data.edit_form.language_id = data.language_id
      data.edit_form.icon = data.editIcon.icon
      let query = data.edit_form
      query.pid == '' ? (query.pid = 0) : false
      request.post('v1/category', query).then((res) => {
        if (res.status == 200) {
          data.editCate = false
          getList()
          ElMessage({
            type: 'success',
            message: res.message,
          })
        } else {
          ElMessage({
            type: 'error',
            message: res.message,
          })
        }
      })
    }
    //清除表单数据
    const clearData = () => {
      data.value = ''
      data.edit_form = {
        id: '',
        language_id: '',
        name: '',
        erp_code: '',
        icon: '',
        level: '',
        pid: '',
      }
    }
    return {
      data,
      handleEdit,
      cancelClick,
      cancel,
      comfirmClick,
      handleDel,
      deleteClick,
      getList,
      handleSizeChange,
      handleCurrentChange,
      handlePreview,
      handleSuccess,
      handleRemove,
      changeIcon,
      changeName,
      onexceed,
      levelList,
      categoryCom,
      errorHandler,
      defaulImg,
      changeCataCom,
      ssflhandleInput,
      getutillist
    }
  },
}
</script>
<style scoped>
::v-deep(.el-upload) {
  position: relative;
}

.el-icon-plus {
  position: absolute;
  width: 28px;
  height: 28px;
  top: calc(50% - 14px);
  left: calc(50% - 14px);
}

::v-deep(.el-upload-list--picture-card) {
  --el-upload-list-picture-card-size: 60px;
}

::v-deep(.is-active .active-icon::after) {
  z-index: 2;
}

::v-deep(.active-icon::after) {
  position: absolute;
  top: 50%;
  left: 15px;
  z-index: 0;
  transform: translateY(-50%);
  content: '下架';
  font-size: 12px;
  font-style: normal;
  color: white;
}

::v-deep(.is-active .unactive-icon::after) {
  z-index: 2;
}

::v-deep(.unactive-icon::after) {
  position: absolute;
  top: 50%;
  right: 15px;
  transform: translateY(-50%);
  z-index: 0;
  content: '上架';
  font-size: 12px;
  font-style: normal;
  color: black;
}

::v-deep(.el-dialog__footer) {
  text-align: left;
  margin-top: 5px;
}

::v-deep(.el-cascader) {
  width: 100%;
}

::v-deep(.el-upload--picture-card),
::v-deep(.el-upload-list--picture-card .el-upload-list__item),
::v-deep(.el-upload-list--picture-card .el-upload-list__item-actions) {
  width: 60px !important;
  height: 60px !important;
}

.bg-open {
  width: 70px;
  background-color: #4178d5;
  line-height: 26px;
  color: #fff;
  font-weight: 600;
  padding: 5px 14px;
  border-radius: 3px;
}

.bg-off {
  width: 70px;
  background-color: #b1b8bf;
  line-height: 26px;
  color: #fff;
  font-weight: 600;
  padding: 5px 14px;
  border-radius: 3px;
}

.m-top {
  margin-bottom: 24px;
}

::v-deep(.el-dialog__footer) {
  text-align: right;
}

::v-deep(.el-button) {
  min-height: 34px;
  padding: 0 10px !important;
}

::v-deep(.el-tree .el-tree-node__expand-icon.expanded) {
  -webkit-transform: rotate(0deg);
  transform: rotate(0deg);
}

/*有子节点 且未展开*/
::v-deep(.el-table .el-table__expand-icon .el-icon-arrow-right:before) {
  background: url('../../assets/default.png') no-repeat;
  content: '';
  display: block;
  width: 16px;
  height: 16px;
  font-size: 16px;
  background-size: 16px;
}

/*有子节点 且已展开*/
::v-deep(.el-table .el-table__expand-icon--expanded) {
  -webkit-transform: rotate(0);
  transform: rotate(0);
}

::v-deep(.el-table
    .el-table__expand-icon--expanded
    .el-icon-arrow-right:before) {
  background: url('../../assets/open.png') no-repeat;
  content: '';
  display: block;
  width: 16px;
  height: 16px;
  font-size: 16px;
  background-size: 16px;
}

/*没有子节点*/
::v-deep(.el-table .el-table__placeholder::before) {
  /* background: url('') no-repeat; */
  content: '';
  display: block;
  width: 16px;
  height: 16px;
  font-size: 16px;
  background-size: 16px;
}

::v-deep(.el-table__expand-icon) {
  vertical-align: middle !important;
}

::v-deep(.el-table__indent) {
  padding-left: 30px !important;
}

::v-deep(.el-table__placeholder) {
  width: 36px !important;
}

::v-deep(tr:not(.el-table__row--level-0):not(.el-table__row--level-1):not(.el-table__row--level-2)
    .el-table_1_column_1
    .cell) {
  margin-left: 23px !important;
}
</style>
