<template>
  <el-form ref="ruleForm" v-loading="loading" label-width="100px" :model="ruleForm" :rules="rules">
    <el-form-item prop="orderCode" style="width: 100%" label="销售订单">
      <el-button class="fr" type="primary" size="mini" style="margin-bottom: 10px" @click="handlePushOrder">添加</el-button>
      <ex-table
        :table="table"
        :data="tableData"
        :columns="columns"
        :size="'mini'"
        :no-pagination="true"
      >
        <template #good_name="{ scope }">
          <span>{{ scope.row.good_name }}</span>
          <span v-for="(si, i) in scope.row.speclist" :key="si.spec_id + i">
            <span v-if="i !== 0">-</span>
            <span v-else>_</span>
            <span>{{ si.spec_name }}[{{ si.spec_value || si.spec_value_name }}]</span>
          </span>
        </template>

        <template #use_type="{ scope }">
          <el-tag size="mini">
            {{
              (usetypeOtions.find(({value}) => value === scope.row.use_type) || {})
                .label || "---"
            }}
          </el-tag>
        </template>

        <template #cgd_status="{ scope }">
          <el-tag size="mini">
            <template v-if="String(scope.row.order_type) === '1'">--</template>
            <template v-else>
              {{
                (
                  purchaseStatusOptions.find(
                    ({ value }) => value === scope.row.cgd_status
                  ) || {}
                ).label || "---"
              }}
            </template>
          </el-tag>
        </template>

        <template #status="{ scope }">
          <el-tag
            :size="tablebtnSize"
            :type="scope.row.status == '0' ? 'warning' : ''"
            v-text="
              (statusOptions.find((item) => item.value == scope.row.status) || {}).label ||
                '--'
            "
          />
        </template>
        <template #order_type="{ scope }">
          <el-tag
            :size="tablebtnSize"
            v-text="
              (
                xs_order_type_options.find((item) => item.id == scope.row.order_type) ||
                {}
              ).label || '--'
            "
          />
        </template>
        <template #order_source="{ scope }">
          <el-tag
            :size="tablebtnSize"
            v-text="
              (
                xs_order_source_options.find(
                  (item) => item.id == scope.row.order_source
                ) || {}
              ).label || '--'
            "
          />
        </template>

        <template #action="{scope}">
          <el-button type="text" size="mini" @click="deleteItem(scope.$index)">删除</el-button>
        </template>
      </ex-table>
    </el-form-item>

    <el-row :gutter="5">
      <el-col :span="12">
        <el-form-item label="业务经理" prop="manager">
          <project-manager
            size="mini"
            :is-detail="true"
            :names="ruleForm.manager"
            :value="ruleForm.managerid"
            @searchChange="manageridChange"
          />
        </el-form-item>
      </el-col>

      <el-col :span="12">
        <el-form-item label="备注" prop="remark">
          <el-input v-model="ruleForm.remark" type="textarea" placeholder="备注" />
        </el-form-item>
      </el-col>
    </el-row>

    <el-form-item>
      <div style="display: flex;justify-content: flex-end">
        <el-button type="primary" size="mini" @click="submit">保存</el-button>
      </div>
    </el-form-item>
    <addEdit
      :company-no="currentCompany"
      :show-model="visible"
      @refresh="handleRefresh"
      @cancel="visible = false"
    />
  </el-form>
</template>

<script>

import { usetypeOtions, xs_order_source_options, xs_order_type_options } from '@/assets/js/statusList'
import asyncRequest from '@/apis/service/dataCorrection/managerCorrection'
import { columns, statusOptions } from './_columns'
import addEdit from './addEdit.vue'
import companyHelper from '@/mixins/companyHelper'

export default {
  name: 'CorrectionForm',
  components: { addEdit },
  mixins: [companyHelper],
  data() {
    return {
      loading: false,
      visible: false,
      xs_order_type_options,
      xs_order_source_options,
      statusOptions,
      usetypeOtions,
      ruleForm: {
        orderCode: [],
        manager: '',
        managerid: '',
        remark: ''
      },
      columns: [
        ...columns.slice(1), {
          width: '100px',
          label: '操作',
          _slot_: 'action',
          fixed: 'right'
        }
      ],
      rules: {
        orderCode: [{ type: 'array', required: true, message: '请选择销售单', trigger: 'change' }],
        manager: [{ required: true, message: '请选择业务经理', trigger: 'change' }],
        remark: [{ required: true, message: '请输入备注', trigger: 'change' }]
      },
      purchaseStatusOptions: [
        { value: '0', label: '待与供应商确认' },
        { value: '1', label: '待入库' },
        { value: '2', label: '部分入库' },
        { value: '3', label: '入库完成' },
        { value: '4', label: '已取消订单' }
      ],
      tablebtnSize: 'mini',
      size: 'mini',
      tableData: [],
      table: {
        stripe: true,
        border: true
      }
    }
  },
  methods: {
    onCompanyChange() {
      this.tableData = []
      this.ruleForm.orderCode = []
      this.$refs.ruleForm.validateField('orderCode')
    },
    handlePushOrder() {
      if (!this.currentCompany) {
        this.$message.warning('请选择一家业务公司')
        return
      }
      this.visible = true
    },
    async submit() {
      if (!this.currentCompany) {
        this.$message.warning('请选择一家业务公司')
        return
      }

      try {
        await this.$refs.ruleForm.validate()
        this.loading = true
        const res = await asyncRequest.add({
          ...this.ruleForm,
          managerid: Array.isArray(this.ruleForm.managerid) ? this.ruleForm.managerid[0] : this.ruleForm.managerid,
          companyNo: this.currentCompany
        })
        this.loading = false

        if (res && res.code === 0 && res.data) {
          this.$router.push('/dataCorrection/managerCorrection')
        } else if (res && res.code >= 100 && res.code <= 104) {
          await this.logout()
        } else {
          this.$message.warning(res.message)
        }
      } catch (e) {
        console.log(e)
      }
    },
    manageridChange(e) {
      const { id, label } = e
      this.ruleForm.manager = label
      this.ruleForm.managerid = id ? [id] : []
      this.$refs.ruleForm.validateField('managerid')
    },
    deleteItem(index) {
      this.tableData.splice(index, 1)
      this.ruleForm.orderCode = this.tableData.map(({ orderCode }) => orderCode)
      this.$refs.ruleForm.validateField('orderCode')
    },
    handleRefresh(selected) {
      const ids = this.tableData.map(({ id }) => id)
      for (const item of selected) {
        if (ids.includes(item.id)) {
          continue
        }
        this.tableData.push(item)
        this.ruleForm.orderCode = this.tableData.map(({ orderCode }) => orderCode)
        this.$refs.ruleForm.validateField('orderCode')
      }
    }
  }
}
</script>
