<template>
  <el-dialog
    title="单次委托"
    v-model="formOpen"
    width="800px"
    append-to-body
    draggable
    @close="cancel"
    :close-on-click-modal = "false"
  >
    <el-form ref="dictRef" :model="form" label-width="100">
      <el-form-item label="客户："> {{ company.name }} </el-form-item>
      <el-form-item label="税号：">
        {{ company.socialCreditCode }}
      </el-form-item>
      <el-form-item>
        <el-checkbox-group v-model="onces" @change="changeDetails">
          <el-checkbox
            v-for="(item, index) in onceTasks"
            :key="index"
            :label="item.id"
            >{{ item.name }}</el-checkbox
          >
        </el-checkbox-group>
        <el-col :span="24">
          <el-row
            v-for="(item, index) in onceDetails"
            :key="index"
            style="
              border-radius: 5px;
              border-color: rgba(0, 0, 0, 20%);
              border-style: solid;
              border-width: 1px;
              margin-bottom: 10px;
            "
          >
            <el-col :span="10" style="padding-top: 18px">
              <el-form-item label="服务项目">
                {{ item.taskTypeName }}
              </el-form-item>
            </el-col>
            <el-col
              v-if="item.payAddress === 0"
              :span="9"
              style="
                padding-top: 18px;
                display: flex;
                flex-direction: column;
                margin-bottom: 18px;
              "
            >
              <el-form-item v-if="item.taskTypeId === '6'" label="变更类型">
                <el-select v-model="item.alterType" style="width: 280px">
                  <el-option
                    v-for="alter in alterTypes"
                    :label="alter.label"
                    :key="alter.value"
                    :value="alter.value"
                  >
                  </el-option>
                </el-select>
              </el-form-item>
              <div
                v-if="item.alterType === '跨区变更'"
                style="margin-left: 60px"
              ></div>
            </el-col>
            <el-col
              :span="24"
              style="padding-top: 5px; padding-left: 33px; margin-bottom: 0px"
            >
              <el-checkbox-group
                v-model="item.processes"
                @change="(arg) => changeProcesses(item, arg)"
                style="display: block; flex-direction: row"
              >
                <el-checkbox
                  v-for="(process, index) in item.defaultProcesses"
                  :key="index"
                  :label="process"
                >
                  <template #default>
                    <div
                      style="
                        display: block;
                        flex-direction: row;
                        width: 45px;
                        justify-content: space-between;
                      "
                    >
                      <div
                        style="
                          display: inline-block;
                          height: 24px;
                          line-height: 24px;
                          margin-right: 10px;
                          width: 80px;
                        "
                      >
                        {{ process.taskTypeDetailName }}
                      </div>
                    </div>
                  </template>
                </el-checkbox>
              </el-checkbox-group>
            </el-col>
          </el-row>
        </el-col>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button
          type="primary"
          icon="Finished"
          size="small"
          @click="submitForm"
          >确 定</el-button
        >
        <el-button @click="cancel" icon="close" size="small">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script setup>
import {
  addEntrust,
  getFactories,
} from "@/api/business/entrust/currentWorkOrder";
import { initTaskTypes } from "@/api/business/crm/contract";

import { rowNum } from "@/utils/index";
import { ref } from "vue";
import { setOneEntrust } from "@/api/business/standardCompany";
import { set } from "@vueuse/core";
// import { fa } from "element-plus/es/locale";

const { proxy } = getCurrentInstance();
const loopTasks = ref([]);
const onces = ref([]);
const onceTasks = ref([]);

const factories = ref([]);
const emit = defineEmits(["choice"]);
const loops = ref([]);
const provinces = ref(proxy.region.getProvinces());
provinces.value.unshift({ code: "", name: "全部" });
const cities = ref([]);
const districts = ref([]);
const toTenantId = ref(null);

const alterTypes = ref([
  {
    value: "普通变更",
    label: "普通变更",
  },
  {
    value: "股权变更",
    label: "股权变更",
  },
  {
    value: "减资",
    label: "减资",
  },
  {
    value: "跨区变更",
    label: "跨区变更",
  },
]);

//地址数组
const provincesArr = ref([]);
const citiesArr = ref([]);
const districtsArr = ref([]);

// 单次任务明细
const onceDetails = ref([]);
const detailEmpty = {
  id: null,
  taskTypeName: "",
  taskTypeId: null,
  serviceNum: undefined,
  freeNum: undefined,
  price: undefined,
  amount: undefined,
  addressStyle: undefined,
  address: undefined,
  fictionAddressId: undefined,
  tenantId: undefined,
  province: "",
  city: "",
  district: "",
  addressStyle: 1,
  provinceId: undefined,
  processes: [],
  defaultProcesses: [],
};

const list = ref([]);

const props = defineProps({
  getList: {
    type: Function,
    default: () => {},
  },
});

const { getList } = toRefs(props);
const startMonth = ref(proxy.moment().format("YYYY-MM-01"));

const formOpen = ref(false);
const company = ref({});
const form = ref({});
const rules = ref({});
const content = ref("请输入员工姓名");
const ids = ref([]);

function submitForm() {
  const formValue = form.value;
  formValue.details = onceDetails.value;
  formValue.formDate = proxy.moment().format("YYYY-MM-DD");
  formValue.companyId = company.value.id;
  formValue.companyName = company.value.name;
  formValue.socialCreditCode = company.value.socialCreditCode;
  if (onceDetails.value.length == 0) {
    proxy.$modal.msgError("请选择服务项目");
  } else {
    setOneEntrust(formValue).then((response) => {
      proxy.$modal.msgSuccess("保存成功!");
      formOpen.value = false;
      getList.value();
    });
  }
}

function checkedProcess(processId, item) {
  const processes = item.processes;
  return processes.findIndex((v) => v.taskTypeDetailId == processId) < 0;
}

function changeProcesses(item) {
  computedItem(item);
  computedService();
}

function computedItem(parent) {
  let amount = 0;
  amount +=
    parent.payAddress === 1 && parent.addressStyle === 2 && parent.addressAmount
      ? Number(parent.addressAmount)
      : 0;
  amount +=
    parent.taskTypeId === "6" &&
    parent.alterType === "跨区变更" &&
    parent.addressStyle === 2 &&
    parent.addressAmount
      ? Number(parent.addressAmount)
      : 0;
  parent.processes.forEach((l) => {
    amount += l.amount ? Number(l.amount) : 0;
  });
  parent.amount = amount;
}
function inputChangeHandler(type, field, item, value, parent) {
  let amount = 0;
  switch (type) {
    case "loop":
      switch (field) {
        case "price":
          amount =
            (item.serviceNum ? Number(item.serviceNum) : 0) *
            (value ? Number(value) : 0);
          item.amount = amount;
          break;
        case "serviceNum":
          amount =
            (item.price ? Number(item.price) : 0) * (value ? Number(value) : 0);
          item.amount = amount;

          break;
        case "freeNum":
          amount =
            (item.price ? Number(item.price) : 0) *
            (item.serviceNum ? Number(item.serviceNum) : 0);
          item.amount = amount;
          break;
      }
      break;
    case "once":
      computedItem(item);
      break;
    case "process":
      computedItem(parent);
      break;
    default:
      break;
  }
  computedService();
}

function computedService() {
  let amount = 0;

  onceDetails.value.forEach((l) => {
    amount +=
      l.payAddress === 1 && l.addressStyle === 2 && l.addressAmount
        ? Number(l.addressAmount)
        : 0;
    l.processes.forEach((v) => {
      amount += v.amount ? Number(v.amount) : 0;
    });
  });

  form.value.amount = amount;
  form.value.trueAmount =
    amount -
    (form.value.discountAmount ? Number(form.value.discountAmount) : 0);
}

function cancel() {
  formOpen.value = false;
  reset();
}

function open(options) {
  company.value = options;
  initTaskTypes().then((res) => {
    onceTasks.value = res.data.onceTasks;
  });
  formOpen.value = true;
}

function handleSelectDistrict(item, index) {
  const _districtCode = item.districtCode;
  const _district = districtsArr.value[index].find((i) => {
    return i.code === _districtCode;
  });
  item.district = _district.name;
}

function delWorkOrderHandler(index) {
  proxy.$modal.confirm("是否确认删除选中的数据项？").then(() => {
    list.value.splice(index, 1);
  });
}

function reset() {
  list.value = [];
  startMonth.value = proxy.moment().format("YYYY-MM-01");
  toTenantId.value = null;
}

function changeDetails() {
  onces.value.forEach((e) => {
    const taskType = onceTasks.value.find((v) => v.id == e);
    if (onceDetails.value.findIndex((v) => v.taskTypeId == e) < 0) {
      const newDetail = JSON.parse(JSON.stringify(detailEmpty));
      newDetail.taskTypeId = e;
      newDetail.taskTypeName = taskType.name;
      newDetail.payAddress = taskType.payAddress;
      (newDetail.alterType = e === "6" ? "普通变更" : ""),
        (newDetail.defaultProcesses = taskType.processes.map((v) => ({
          taskTypeId: e,
          taskTypeDetailId: v.id,
          taskTypeDetailName: v.name,
          fictionAddressId: null,
          fictionAddress: "",
          addressStyle: 0,
          checked: false,
          amount: undefined,
        })));
      newDetail.processes = [];
      onceDetails.value.push(newDetail);
    }
  });
  onceDetails.value = onceDetails.value.filter(
    (v) => onces.value.findIndex((e) => e == v.taskTypeId) > -1
  );

  let provincesLength = provincesArr.value.length;

  if (onceDetails.value.length > provincesLength) {
    for (let i = 0; i < onceDetails.value.length - provincesLength; i++) {
      provincesArr.value.push(provinces.value);
      citiesArr.value.push(cities.value);
      districtsArr.value.push(districts.value);
    }
  } else if (onceDetails.value.length < provincesLength) {
    for (let i = 0; i < provincesLength - onceDetails.value.length; i++) {
      provincesArr.value.length--;
      citiesArr.value.length--;
      districtsArr.value.length--;
    }
  }
}

function initFactories() {
  getFactories().then((res) => {
    factories.value = res.data;
  });
}
initFactories();
// 暴露给父组件的方法
defineExpose({
  open,
  cancel,
});
</script>