<template>
  <div class="app-container">
    <el-form
      ref="formLabelAlign"
      label-width="120px"
      :model="formLabelAlign"
      :rules="rules"
    >
      <el-form-item label="服务商名称：" prop="name">
        <el-input v-model="formLabelAlign.name" placeholder="请输入服务商名称" />
      </el-form-item>
      <el-form-item label="服务商级别：" prop="serviceLevel">
        <el-select v-model="formLabelAlign.serviceLevel" placeholder="请选择服务商级别">
          <el-option
            v-for="i in serviceLevel"
            :key="i.id"
            :label="i.value"
            :value="i.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="服务商地区：" prop="address">
        <!--<el-cascader
          ref="cascader"
          :key="areaKey"
          v-model="formLabelAlign.area"
          :class="{ display: cascaderDisplay }"
          clearable
          :props="cascaderProps"
          style="width: 100%"
          :placeholder="cascaderPlaceholder"
          @change="handleChange"
        />-->
        <el-input v-model="formLabelAlign.address" placeholder="请服务商地区" />
      </el-form-item>
      <el-form-item label="服务商类型：" prop="serviceCategory">
        <el-select v-model="formLabelAlign.serviceCategory" placeholder="服务商类型">
          <el-option
            v-for="i in serviceCategoryList"
            :key="i.id"
            :label="i.value"
            :value="i.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="联系人：" prop="linkMan">
        <el-input v-model="formLabelAlign.linkMan" placeholder="请输入联系人" />
      </el-form-item>
      <el-form-item label="联系电话：" prop="mobile">
        <el-input
          v-model="formLabelAlign.mobile"
          placeholder="请输入联系电话"
          :maxlength="11"
          oninput="value=value.replace(/[^\d]/g, '')"
        />
      </el-form-item>
      <el-form-item label="简介图：" prop="textRelateds">
        <image-upload
          :limit="6"
          :image-list="textRelateds"
          @success="handleImageSuccess($event, 'textRelateds')"
          @remove="handleImageRemove($event, 'textRelateds')"
        />
      </el-form-item>
      <el-form-item label="简介：" prop="text">
        <el-input
          v-model="formLabelAlign.text"
          type="textarea"
          :autosize="{ minRows: 8, maxRows: 10 }"
          placeholder="请输入内容"
        />
      </el-form-item>
      <el-form-item v-if="id" label="资格证书：">
        <el-image style="width: 200px;" :src="qualificationImage" :preview-src-list="[qualificationImage]" />
      </el-form-item>
      <el-form-item label="资料上传：" prop="infoRelateds">
        <file-upload
          :list="infoList"
          :limit="20"
          :tip="'支持上传pdf、docx、 pptx文件格式'"
          :before-upload="beforeUpload"
          :is-check="false"
          @success="uploadSuccess($event, 'infoRelateds')"
          @change="uploadChange($event, 'infoRelateds')"
          @remove="handleRemove($event, 'infoRelateds')"
        />
      </el-form-item>
      <div v-if="!id">
        <el-form-item label="合同：">
          （由于是添加新服务商，必须添加合同，后续可去合同列表编辑及添加）
        </el-form-item>
        <el-form-item label="合同编号：" prop="contract.contractId">
          <el-input v-model="formLabelAlign.contract.contractId" />
        </el-form-item>
        <el-form-item label="合同起始日期：" prop="contract.contractStartDate">
          <el-date-picker
            v-model="formLabelAlign.contract.contractStartDate"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择日期"
          />
        </el-form-item>
        <el-form-item label="合同截止日期：" prop="contract.contractEndDate">
          <el-date-picker
            v-model="formLabelAlign.contract.contractEndDate"
            type="date"
            placeholder="选择日期"
            value-format="yyyy-MM-dd"
          />
        </el-form-item>
        <el-form-item label="上传合同：" prop="contract.contractRelateds">
          <file-upload
            :limit="20"
            :is-check="false"
            :file-list="contractList"
            :tip="'支持上传pdf、docx、 pptx文件格式'"
            @success="contractUploadSuccess($event)"
            @remove="contractHandleRemove($event)"
          />
        </el-form-item>
      </div>
      <el-form-item>
        <el-button type="primary" @click="submitForm('formLabelAlign')">保存</el-button>
        <el-button @click="$router.back()">返回</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import ImageUpload from '@/components/UploadImage/index.vue'
import FileUpload from '../components/UploadFile.vue'
import {
  getAddress,
  addProvider,
  getProviderDetail
} from '@/api/serviceSettlement/service'
import serviceMixin from '../mixin/index'
import { mapGetters } from 'vuex'

export default {
  components: {
    ImageUpload,
    FileUpload
  },
  mixins: [serviceMixin],
  data() {
    return {
      formLabelAlign: {
        address: '',
        infoRelateds: [],
        area: [],
        textRelateds: [],
        contract: {
          contractRelateds: []
        }
      },
      qualificationImage: '',
      infoList: [],
      contractList: [],
      textRelateds: [],
      areaKey: 0,
      rules: {
        name: [
          { required: true, message: '请输入服务商名称', trigger: 'blur' },
          { max: 50, message: '长度最多50个汉字', trigger: 'blur' }
        ],
        address: [{ required: true, message: '请输入地址', trigger: 'blur' }],
        serviceLevel: [
          { required: true, message: '请选择服务商级别', trigger: 'change' }
        ],
        mobile: [{ required: true, message: '请输入联系电话', trigger: 'blur' }],
        linkMan: [{ required: true, message: '请输入联系人', trigger: 'blur' }],
        serviceCategory: [
          { required: true, message: '请选择服务商类型', trigger: 'change' }
        ],
        textRelateds: [{ required: true, message: '请上传简介图', trigger: 'change' }],
        contract: {
          contractId: [{ required: true, message: '请输入合同编号', trigger: 'blur' }],
          contractStartDate: [
            { required: true, message: '请选择合同起始时间', trigger: 'change' }
          ],
          contractEndDate: [
            { required: true, message: '请选择合同结束时间', trigger: 'change' }
          ],
          contractRelateds: [
            { required: true, message: '请上传合同文件', trigger: 'change' }
          ]
        }
      }
    }
  },
  computed: {
    ...mapGetters(['userId', 'username', 'fullName', 'phone']),
    id() {
      return this.$route.query.id || false
    },
    cascaderPlaceholder() {
      return this.cascaderDisplay ? this.formLabelAlign.address : '请选择所在区域'
    },
    cascaderDisplay() {
      return this.formLabelAlign.area.length > 0
    },
    // 级联选择器
    cascaderProps() {
      return {
        lazy: true,
        lazyLoad: async(node, resolve) => {
          const { level, data } = node
          console.log(node)
          const result = await getAddress({ parentId: data?.vId || 0, type: level })
          const nodes = result.data.map((item) => ({
            value: item.name,
            label: item.name,
            leaf: level >= 1,
            vId: item.id
          }))
          resolve(nodes)
        }
      }
    }
  },
  mounted() {
    if (this.id) {
      this.getInfo()
    }
  },
  methods: {
    async getInfo() {
      const { data } = await getProviderDetail({ providersId: this.id })
      this.formLabelAlign = data
      this.infoList = data.infoRelateds.map((e, i) => ({ name: e.fileName, response: { data: e.image }}))
      this.textRelateds = data.textRelateds.map((e, i) => ({ uid: i, url: e.image }))
      this.formLabelAlign.area = data.address.split('/').map(e => e.trim())
      this.qualificationImage = data.qualificationImage
    },
    // 地区选择
    handleChange($event) {
      console.log($event)
      this.formLabelAlign.address = $event.join(' / ')
    },
    // 合同上传
    contractUploadSuccess($event) {
      this.formLabelAlign.contract.contractRelateds = $event.fileList.map(e => ({ image: e.response?.data || '', fileName: e.name }))
    },
    contractHandleRemove($event) {
      this.formLabelAlign.contract.contractRelateds = $event.fileList.map(e => ({ image: e.response?.data || '', fileName: e.name }))
    },
    submitForm(form) {
      console.log(this.formLabelAlign)
      this.$refs[form].validate(async(valid) => {
        if (valid) {
          try {
            delete this.formLabelAlign.area
            const form = Object.assign(this.formLabelAlign, { createBy: this.fullName })
            await addProvider(form)
            this.$message({ type: 'success', message: '添加成功' })
            this.$router.back()
          } catch (e) {
            console.warn(e)
          }
        }
      })
    },
    beforeUpload(file) {
      console.log(file)
      if (file.size / 1024 / 1024 < 50) {
        return true
      } else {
        this.$message({
          type: 'error',
          message: '文件大小限制在50M以内'
        })
        return false
      }
    },
    handleImageRemove($event, name) {
      console.log($event, name)
      this.formLabelAlign[name] = $event.fileList.map(e => ({
        image: e.url
      }))
    },
    handleImageSuccess($event, name) {
      console.log($event)
      this.formLabelAlign[name] = $event.fileList.map(e => ({
        image: e.response ? e.response.data : e.url
      }))
    }
  }
}
</script>

<style lang="scss" scoped>
::v-deep .el-input,
::v-deep .el-textarea__inner {
  width: 500px;
}
::v-deep .el-form {
  width: 650px;
  margin: 0 auto;
}
</style>
